删除NSString中的多个空格

我有一个NSString ,这有多个空格,我想修剪这些空格,并为@例如@“…….. …….你”做一个单独的空间到@“你好吗”(点只是空格)

我曾尝试过

 NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; 

它似乎没有工作。 任何想法。

你可以使用一个正则expression式来完成这个工作:

 NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" +" options:NSRegularExpressionCaseInsensitive error:&error]; 

模式是一个空间,然后是一个或多个空间。 将其replace为string中的单个空格:

 NSString *trimmedString = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [user_ids length]) withTemplate:@" "]; 

这工作时,我试了一下:

 NSString *trimmedString = @"THIS IS A TEST S STRING SDDF "; while ([trimmedString rangeOfString:@" "].location != NSNotFound) { trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@" "]; } NSLog(@"%@", trimmedString); 

user1587011

 NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; 

这个string方法用于删除开始处的空格和最后一个string。

试试这个给你你想要的:

 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:@" "]; 

所选答案的Swift 3代码

 let regex = try? NSRegularExpression(pattern: " +", options: .caseInsensitive) let trimmedString: String? = regex?.stringByReplacingMatches(in: user_ids, options: [], range: NSRange(location: 0, length: user_ids.characters.count), withTemplate: " ") 
 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}+" options:NSRegularExpressionCaseInsensitive error:&error]; user_ids = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [s length]) withTemplate:@" "]; 
 NSString* NSStringWithoutSpace(NSString* string) { return [string stringByReplacingOccurrencesOfString:@" " withString:@""]; } 

您可以使用:

 NSString *trimmedString = [user_ids stringByReplacingOccurrencesOfString: @" " withString:@""];