私はこのような正規表現を使用することを好みます:
NSString *myString = @"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [myStringlength])];
//myNewString will be @"thisisatest"
あなた自身をNSStringのカテゴリにして、人生をさらに簡単にすることができます:
- (NSString *) removeAllWhitespace
{
return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [self length])];
}
これもユニットテストメソッドです:
- (void) testRemoveAllWhitespace
{
NSString *testResult = nil;
NSArray *testStringsArray = @[@""
,@" "
,@" basicTest "
,@" another Test \n"
,@"a b c d e f g"
,@"\n\tA\t\t \t \nB \f C \t ,d,\ve F\r\r\r"
,@" landscape, portrait, ,,,up_side-down ;asdf; lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & * * ()+ + "
];
NSArray *expectedResultsArray = @[@""
,@""
,@"basicTest"
,@"anotherTest"
,@"abcdefg"
,@"ABC,d,eF"
,@"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!@@##$$%^^&**()++"
];
for (int i=0; i < [testStringsArray count]; i++)
{
testResult = [testStringsArray[i] removeAllWhitespace];
STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"",
testStringsArray[i], expectedResultsArray[i], testResult);
}
}