Answers:
使用hfossli提供的本机regexp解决方案。
使用您喜欢的正则表达式库或使用以下可可本地解决方案:
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:@" "];
正则表达式和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+
易于扩展,性能高,代码行数少以及创建的对象数使此解决方案变得合适。
stringByReplacingOccurrencesOfString:
。不敢相信我不知道。
实际上,有一个非常简单的解决方案:
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)
(来源)
使用正则表达式,但不需要任何外部框架:
NSString *theString = @" Hello this is a long string! ";
theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, theString.length)];
NSRegularExpressionSearch
说,它仅适用于以下rangeOfString:...
方法
一线解决方案:
NSString *whitespaceString = @" String with whitespaces ";
NSString *trimmedString = [whitespaceString
stringByReplacingOccurrencesOfString:@" " withString:@""];
这应该做...
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:@" "];
regex的另一个选项是RegexKitLite,它很容易嵌入到iPhone项目中:
[theString stringByReplacingOccurencesOfRegex:@" +" withString:@" "];
下面是一个片段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;
}
替代解决方案:为自己获取OgreKit(可可正则表达式库)的副本。
整个函数如下:
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);
简短而甜美。
如果您追求最快的解决方案,那么精心设计的一系列使用说明NSScanner
可能会效果最好,但这仅在您计划处理巨大(许多兆字节)的文本块时才需要。
@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"
您也可以使用简单的while参数。那里没有RegEx魔术,所以也许将来更容易理解和更改:
while([yourNSStringObject replaceOccurrencesOfString:@" "
withString:@" "
options:0
range:NSMakeRange(0, [yourNSStringObject length])] > 0);
根据要求,以下两个正则表达式将起作用
然后应用nsstring的instance方法stringByReplacingOccurrencesOfString:withString:options:range:
将其替换为单个空格。
例如
[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
注意:对于iOS 5.x及更高版本,我没有为上述功能使用'RegexKitLite'库。