次のコードで文字列をフィルタリングしようとしています。
//the String with the original text
NSString *unfilteredString = @"( A1 )";
//initialize a string that will hold the result
NSMutableString *resultString = [NSMutableString stringWithCapacity:unfilteredString.length];
NSScanner *scanner = [NSScanner scannerWithString:unfilteredString];
NSCharacterSet *allowedChars = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:allowedChars intoString:&buffer]) {
[resultString appendString:buffer];
}
else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog (@"Result: %@", resultString);
結果が得られます:
結果: ( A)
ご覧のとおり、数字の 1 だけでなく末尾のスペースも削除されています。
ヒントはありますか?