23

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.

8 Answers 8

47

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:@" "];
4
  • I have tried Madhavan, It is removing full spaces between words.
    – Newbee
    Aug 27, 2012 at 6:45
  • @user1587011 Is that not what you require? Are you saying that it removes spaces, but not replaces them with a single space?
    – MadhavanRP
    Aug 27, 2012 at 6:52
  • NSString *trimmedString = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [user_ids length]) withTemplate:@" "];(given double space in template. Its working now. thanks...
    – Newbee
    Aug 27, 2012 at 7:00
  • Make sure user_ids != nil. Also if you're doing this a lot, make sure not to create regex every time.
    – Peter
    Sep 5, 2013 at 21:22
12

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);
5
  • I liked this answer the best
    – William T.
    May 10, 2013 at 21:52
  • It's been a while since I've seen an infinite loop Jan 15, 2016 at 6:46
  • It is an infinite loop. you are replacing the same string with the same string Have you gone through with the code before posting here?
    – iEinstein
    Mar 21, 2016 at 7:04
  • 2
    Dude it was a one character typo calm down. Its fixed now.
    – WolfLink
    Mar 24, 2016 at 20:13
  • YES, This elegant and perfect!
    – John
    Aug 20, 2017 at 20:22
11

user1587011

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:@" "];
1
  • 2
    +1 for filteredArrayUsingPredicate and componentsJoinedByString
    – ZYiOS
    Nov 24, 2013 at 16:27
1

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

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

Swift 4:

let stringOut = stringIn.replacingOccurrences(of: " +", with: " ", options: String.CompareOptions.regularExpression, range: nil)
-1
NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
1
  • Please elaborate on how this code answers the question.
    – JAL
    Jun 21, 2016 at 22:50
-3

you can use:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.