考虑以下示例:
" Hello this is a long string! "
我想把它转换成:
"Hello this is a long string!"
发布于 2009-09-15 13:36:34
OS X 10.7+和iOS 3.2+
使用hfossli提供的原生regexp solution。
否则
使用您最喜欢的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:@" "];
发布于 2009-09-15 13:18:22
实际上,有一个非常简单的解决方案:
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)
(Source)
发布于 2010-11-04 18:19:36
使用正则表达式,但不需要任何外部框架:
NSString *theString = @" Hello this is a long string! ";
theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, theString.length)];
https://stackoverflow.com/questions/758212
复制相似问题