次の例を検討してください。
" Hello this is a long string! "
私はそれを次のように変換したい:
"Hello this is a long string!"
次の例を検討してください。
" Hello this is a long string! "
私はそれを次のように変換したい:
"Hello this is a long string!"
hfossli が提供するネイティブの正規表現ソリューションを使用します。
お気に入りの正規表現ライブラリを使用するか、次の Cocoa ネイティブ ソリューションを使用します。
NSString *theString = @" Hello this is a long string! ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];
実際、それには非常に簡単な解決策があります。
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)
(ソース)
正規表現を使用しますが、外部フレームワークは必要ありません。
NSString *theString = @" Hello this is a long string! ";
theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, theString.length)];
1行のソリューション:
NSString *whitespaceString = @" String with whitespaces ";
NSString *trimmedString = [whitespaceString
stringByReplacingOccurrencesOfString:@" " withString:@""];
これで済むはず…
NSString *s = @"this is a string with lots of white space";
NSArray *comps = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *words = [NSMutableArray array];
for(NSString *comp in comps) {
if([comp length] > 1)) {
[words addObject:comp];
}
}
NSString *result = [words componentsJoinedByString:@" "];
正規表現のもう 1 つのオプションはRegexKitLite です。これは、iPhone プロジェクトに非常に簡単に埋め込むことができます。
[theString stringByReplacingOccurencesOfRegex:@" +" withString:@" "];
これを試して
NSString *theString = @" Hello this is a long string! ";
while ([theString rangeOfString:@" "].location != NSNotFound) {
theString = [theString stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
NSStringこれは拡張機能のスニペットです。"self"はNSStringインスタンスです。2 つの引数を渡すことで[NSCharacterSet whitespaceAndNewlineCharacterSet]、連続する空白を 1 つのスペースにまとめるために使用できます。' '
- (NSString *) stringCollapsingCharacterSet: (NSCharacterSet *) characterSet toCharacter: (unichar) ch {
int fullLength = [self length];
int length = 0;
unichar *newString = malloc(sizeof(unichar) * (fullLength + 1));
BOOL isInCharset = NO;
for (int i = 0; i < fullLength; i++) {
unichar thisChar = [self characterAtIndex: i];
if ([characterSet characterIsMember: thisChar]) {
isInCharset = YES;
}
else {
if (isInCharset) {
newString[length++] = ch;
}
newString[length++] = thisChar;
isInCharset = NO;
}
}
newString[length] = '\0';
NSString *result = [NSString stringWithCharacters: newString length: length];
free(newString);
return result;
}
要件に応じて、次の 2 つの正規表現が機能します。
次に、nsstring のインスタンス メソッドstringByReplacingOccurrencesOfString:withString:options:range:を適用して、それらを 1 つの空白に置き換えます。
例えば
[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
注: iOS 5.x 以降では、上記の機能に「RegexKitLite」ライブラリを使用しませんでした。
別の解決策: OgreKit (Cocoa 正規表現ライブラリ) のコピーを入手してください。
関数全体は次のようになります。
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);
短くて甘い。
最速のソリューションを求めている場合は、慎重に構築された一連の命令を使用するのNSScannerがおそらく最も効果的ですが、それが必要になるのは、膨大な (数メガバイトの) テキスト ブロックを処理する場合に限られます。
@Mathieu Godartによると、最良の回答ですが、一部の行が欠落しています。すべての回答は単語間のスペースを減らすだけですが、タブがある場合、またはスペースにタブがある場合、次のように: " this is text \t , and\tTab between ,同様に " 3 行のコードで次のことを行います: 空白を減らしたい文字列
NSString * str_aLine = @" this is text \t , and\tTab between , so on ";
// replace tabs to space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
// reduce spaces to one space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@" +" withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, str_aLine.length)];
// trim begin and end from white spaces
str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
結果は
"this is text , and Tab between , so on"
タブを置き換えないと、結果は次のようになります。
"this is text , and Tab between , so on"