回答:
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:@" "];正規表現とNSCharacterSetはあなたを助けるためにここにあります。このソリューションは、先頭と末尾の空白、および複数の空白を削除します。
NSString *original = @"    Hello      this  is a   long       string!   ";
NSString *squashed = [original stringByReplacingOccurrencesOfString:@"[ ]+"
                                                         withString:@" "
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, original.length)];
NSString *final = [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];ロギングfinalにより
"Hello this is a long string!"可能な代替正規表現パターン:
[ ]+[ \\t]+\\s+拡張の容易さ、パフォーマンス、コードの行数、作成されるオブジェクトの数により、このソリューションは適切です。
stringByReplacingOccurrencesOfString:。知らなかったなんて信じられない。
                    実際には、非常に簡単な解決策があります。
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)];NSRegularExpressionSearchは、rangeOfString:...メソッドでのみ機能することが記載されています
                    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拡張機能からのスニペットです。"self"はNSStringインスタンスです。渡すことによって、単一の空間に連続した空白を収納するために使用される[NSCharacterSet whitespaceAndNewlineCharacterSet]と、' '二つの引数に。
- (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;
}代替ソリューション:OgreKit(Cocoa正規表現ライブラリ)のコピーを自分で入手します。
関数全体は次のようになります。
NSString *theStringTrimmed =
   [theString stringByTrimmingCharactersInSet:
        [NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression  *regex =
    [OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);短くて甘い。
最速のソリューションNSScannerが必要な場合は、慎重に作成された一連の命令を使用するのがおそらく最も効果的ですが、これは、巨大な(数メガバイトの)テキストブロックを処理する場合にのみ必要です。
@Mathieu Godartによると最良の回答ですが、一部の行が欠落しています。すべての回答は単語間のスペースを減らします。のように "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"タブを置き換えなければ、resulは次のようになります。
"this is text    , and  Tab between , so on"単純なwhile引数を使用することもできます。そこにはRegExマジックはないので、将来的には理解して変更する方が簡単かもしれません。
while([yourNSStringObject replaceOccurrencesOfString:@"  "
                         withString:@" "
                         options:0
                         range:NSMakeRange(0, [yourNSStringObject length])] > 0);次の2つの正規表現は要件に応じて機能します
次に、nsstringのインスタンスメソッドを適用します。 stringByReplacingOccurrencesOfString:withString:options:range:をして、それらを単一の空白で置き換えます。
例えば
[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];注:iOS 5.x以降では、上記の機能に「RegexKitLite」ライブラリを使用しませんでした。