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-native 解决方案:

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 回答
53

Regex 和 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+

性能概要

易于扩展、性能、代码行数和创建的对象数量使得该解决方案非常合适。

于 2013-08-06T15:04:24.620 回答
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

单线解决方案:

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

正则表达式的另一个选项是RegexKitLite,它很容易嵌入到 iPhone 项目中:

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

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;
}
于 2009-04-16T22:55:53.063 回答
3

尝试这个

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

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

替代解决方案:为自己获取一份 OgreKit(Cocoa 正则表达式库)。

  • OgreKit(日文网页——代码为英文)
  • OgreKit(谷歌自动翻译):

那么整个函数是:

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

短而甜。

如果您追求最快的解决方案,那么精心构建的一系列指令使用NSScanner可能效果最好,但只有在您计划处理大量(数兆字节)文本块时才需要这样做。

于 2009-04-16T23:40:51.600 回答
-1

以下两个正则表达式将根据要求起作用

  1. @"+" 用于匹配空格和制表符
  2. @"\\s{2,}" 用于匹配空格、制表符和换行符

然后应用 nsstring 的实例方法stringByReplacingOccurrencesOfString:withString:options:range:将它们替换为单个空格。

例如

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

注意:我没有为 iOS 5.x 及更高版本的上述功能使用“RegexKitLite”库。

于 2013-07-19T17:55:01.137 回答
-1

根据@Mathieu Godart 的最佳答案,但缺少某些行,所有答案只会减少单词之间的空间,但是当有制表符或制表符在适当的空间时,如下所示:“这是文本 \t 和 \tTab 之间,以此类推" 在三行代码中,我们将:我们想要减少空格的字符串

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 回答
-1

您还可以使用简单的 while 参数。那里没有 RegEx 魔法,所以将来可能更容易理解和改变:

while([yourNSStringObject replaceOccurrencesOfString:@"  "
                         withString:@" "
                         options:0
                         range:NSMakeRange(0, [yourNSStringObject length])] > 0);
于 2013-11-17T14:29:41.117 回答