考虑以下示例:
" Hello this is a long string! "
我想将其转换为:
"Hello this is a long string!"
考虑以下示例:
" Hello this is a long string! "
我想将其转换为:
"Hello this is a long string!"
使用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:@" "];
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+
易于扩展、性能、代码行数和创建的对象数量使得该解决方案非常合适。
实际上,有一个非常简单的解决方案:
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)];
单线解决方案:
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:@" "];
正则表达式的另一个选项是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;
}
尝试这个
NSString *theString = @" Hello this is a long string! ";
while ([theString rangeOfString:@" "].location != NSNotFound) {
theString = [theString stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
替代解决方案:为自己获取一份 OgreKit(Cocoa 正则表达式库)。
那么整个函数是:
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);
短而甜。
如果您追求最快的解决方案,那么精心构建的一系列指令使用NSScanner
可能效果最好,但只有在您计划处理大量(数兆字节)文本块时才需要这样做。
以下两个正则表达式将根据要求起作用
然后应用 nsstring 的实例方法stringByReplacingOccurrencesOfString:withString:options:range:
将它们替换为单个空格。
例如
[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
注意:我没有为 iOS 5.x 及更高版本的上述功能使用“RegexKitLite”库。
根据@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);