NSString删除空格,只留一个空格

时间:2013-01-26 08:18:45

标签: objective-c parsing nsstring

  

可能重复:
  How do you remove extra empty space in NSString?

我正在试图弄清楚如何从字符串中删除所有空格但只留下一个空格。 那就是我有一个像

这样的字符串
"this    is  my     test  string"

结果将是

"this is my test string"

谢谢

更新:在此处找到答案 Removing multiple spaces in NSString

1 个答案:

答案 0 :(得分:3)

你可以尝试这个:

NSString *string=@"this    is  my     test  string";

NSCharacterSet *spaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *tempArray = [[string componentsSeparatedByCharactersInSet:spaces] filteredArrayUsingPredicate:predicate];
string = [tempArray componentsJoinedByString:@" "];