122

次の例を検討してください。

"    Hello      this  is a   long       string!   "

私はそれを次のように変換したい:

"Hello this is a long string!"
4

13 に答える 13

125

OS X 10.7 以降および iOS 3.2 以降

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:@" "];
于 2009-09-15T13:36:33.820 に答える
41

実際、それには非常に簡単な解決策があります。

NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)

ソース

于 2009-09-15T13:18:21.860 に答える
13

正規表現を使用しますが、外部フレームワークは必要ありません。

NSString *theString = @"    Hello      this  is a   long       string!   ";

theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
                       options:NSRegularExpressionSearch
                       range:NSMakeRange(0, theString.length)];
于 2010-11-04T10:19:35.640 に答える
9

1行のソリューション:

NSString *whitespaceString = @" String with whitespaces ";

NSString *trimmedString = [whitespaceString
        stringByReplacingOccurrencesOfString:@" " withString:@""];
于 2010-08-03T08:41:49.447 に答える
6

これで済むはず…

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:@" "];
于 2009-04-16T23:24:33.993 に答える
4

正規表現のもう 1 つのオプションはRegexKitLite です。これは、iPhone プロジェクトに非常に簡単に埋め込むことができます。

[theString stringByReplacingOccurencesOfRegex:@" +" withString:@" "];
于 2009-04-17T04:42:17.833 に答える
3

これを試して

NSString *theString = @"    Hello      this  is a   long       string!   ";

while ([theString rangeOfString:@"  "].location != NSNotFound) {
    theString = [theString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
}
于 2012-03-15T07:25:58.390 に答える
3

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;
}
于 2009-04-16T22:55:53.063 に答える
-1

要件に応じて、次の 2 つの正規表現が機能します。

  1. @" +" 空白とタブの一致
  2. @"\\s{2,}" は、空白、タブ、および改行に一致します

次に、nsstring のインスタンス メソッドstringByReplacingOccurrencesOfString:withString:options:range:を適用して、それらを 1 つの空白に置き換えます。

例えば

[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];

注: iOS 5.x 以降では、上記の機能に「RegexKitLite」ライブラリを使用しませんでした。

于 2013-07-19T17:55:01.137 に答える
-1

別の解決策: OgreKit (Cocoa 正規表現ライブラリ) のコピーを入手してください。

  • OgreKit (日本語の Web ページ -- コードは英語)
  • OgreKit (Google 自動翻訳):

関数全体は次のようになります。

NSString *theStringTrimmed =
   [theString stringByTrimmingCharactersInSet:
        [NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression  *regex =
    [OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);

短くて甘い。

最速のソリューションを求めている場合は、慎重に構築された一連の命令を使用するのNSScannerがおそらく最も効果的ですが、それが必要になるのは、膨大な (数メガバイトの) テキスト ブロックを処理する場合に限られます。

于 2009-04-16T23:40:51.600 に答える
-1

@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"
于 2012-02-02T08:49:09.123 に答える