将空白序列折叠为单个字符和修剪字符串

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (13)

考虑以下示例:

"    Hello      this  is a   long       string!   "

我想把它转化为:

"Hello this is a long string!"
提问于
用户回答回答于

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+

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

用户回答回答于

要么使用最喜欢的regexp库,要么使用以下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:@" "];

扫码关注云+社区