Removing multiple spaces in NSString

ios, iphone, objective-c

Solution

You could use a regular expression to accomplish this:

NSError *error = nil;

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

The pattern is a space followed by one or more occurrences of space. Replace this with a single space in your string:

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

Problem

I have a `NSString`, this has multiple spaces, I want to trim those spaces and make a single space for e.g.@"how.....are.......you" into @"how are you".(dots are simply spaces) I have tried with ``` NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; ``` It not seems to work. Any idea.

Original source