objective-c - 将空格序列折叠成单个字符并修剪字符串

考虑以下示例:

"    Hello      this  is a   long       string!   "

我想把它转换成:

"Hello this is a long string!"

最佳答案

OS X 10.7+ 和 iOS 3.2+

使用原生 regexp solution由 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:@" "];

https://stackoverflow.com/questions/758212/

相关文章:

objective-c - 在框架模块中包含非模块化 header

iphone - -all_load 链接器标志有什么作用?

iphone - SplitView 就像 iPhone 上的 Facebook 应用程序

objective-c - 如何使用 NSNotificationCenter 传递对象

objective-c - NSPredicate:按 NSDate 属性的日期过滤对象

iphone - 使用 Cocoa 和 Objective-C 理解引用计数

objective-c - 如何在 iPhone 模拟器中更改时间和时区?

iphone - Storyboard - 引用 AppDelegate 中的 ViewContro

jquery - 你能在 iPad 上自动播放 HTML5 视频吗?

objective-c - 为什么 Objective-C 不支持私有(private)方法?