Removing multiple spaces in NSString

7 Solutions Collect From Internet About “Removing multiple spaces in NSString”

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

This worked when I tried it:

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


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

this string method used to remove spaces at begining and last of a string.

Try this it gives you what you want:–

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:@" "];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s{2,}+" options:NSRegularExpressionCaseInsensitive error:&error];

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

Swift 3 code of the selected answer

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: " ")
NSString* NSStringWithoutSpace(NSString* string)
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];

you can use:

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