【发布时间】:2010-10-19 23:34:49
【问题描述】:
考虑以下示例:
" Hello this is a long string! "
我想把它转换成:
"Hello this is a long string!"
【问题讨论】:
标签: objective-c ios nsstring
考虑以下示例:
" Hello this is a long string! "
我想把它转换成:
"Hello this is a long string!"
【问题讨论】:
标签: objective-c ios nsstring
这是来自 NSString 扩展的 sn-p,其中 "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 *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:@" "];
【讨论】:
替代解决方案:为自己获取一份 OgreKit(Cocoa 正则表达式库)。
那么整个函数就是:
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);
又短又甜。
如果您追求最快的解决方案,使用NSScanner 精心构建的一系列指令可能效果最好,但只有在您计划处理大量(数兆字节)文本块时才需要这样做。
【讨论】:
正则表达式的另一个选项是RegexKitLite,它很容易嵌入到 iPhone 项目中:
[theString stringByReplacingOccurencesOfRegex:@" +" withString:@" "];
【讨论】:
其实,有一个非常简单的解决方案:
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)
(Source)
【讨论】:
使用hfossli提供的原生regexp solution。
使用您最喜欢的正则表达式库或使用以下 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:@" "];
【讨论】:
单行解决方案:
NSString *whitespaceString = @" String with whitespaces ";
NSString *trimmedString = [whitespaceString
stringByReplacingOccurrencesOfString:@" " withString:@""];
【讨论】:
使用正则表达式,但不需要任何外部框架:
NSString *theString = @" Hello this is a long string! ";
theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, theString.length)];
【讨论】:
NSRegularExpressionSearch 的文档说它只适用于 rangeOfString:... 方法
根据@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"
【讨论】:
试试这个
NSString *theString = @" Hello this is a long string! ";
while ([theString rangeOfString:@" "].location != NSNotFound) {
theString = [theString stringByReplacingOccurrencesOfString:@" " withString:@" "];
}
【讨论】:
根据需求,遵循两个正则表达式会起作用
然后应用 nsstring 的实例方法stringByReplacingOccurrencesOfString:withString:options:range: 将它们替换为单个空格。
例如
[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
注意:对于 iOS 5.x 及更高版本的上述功能,我没有使用“RegexKitLite”库。
【讨论】:
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+
易于扩展、性能、代码行数和创建的对象数量使此解决方案非常合适。
【讨论】:
stringByReplacingOccurrencesOfString: 中使用正则表达式。不敢相信我不知道。
您也可以使用简单的 while 参数。那里没有 RegEx 魔法,所以将来可能更容易理解和改变:
while([yourNSStringObject replaceOccurrencesOfString:@" "
withString:@" "
options:0
range:NSMakeRange(0, [yourNSStringObject length])] > 0);
【讨论】: