122

Consider the following example:

"    Hello      this  is a   long       string!   "

I want to convert that to:

"Hello this is a long string!"

13 Answers 13

124

OS X 10.7+ and iOS 3.2+

Use the native regexp solution provided by hfossli.

Otherwise

Either use your favorite regexp library or use the following Cocoa-native solution:

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:@" "];
11
  • 4
    I'd be curious of a performance comparison of this to a regex replacement with a trim to remove the ends. On the one hand, you have a regex to deal with. On the other, you have a predicate. Either requires internal processing of the respective expressions.
    – lilbyrdie
    Commented Jun 23, 2011 at 15:30
  • @lilbyrdie: This depends on the string I think, how many whitespaces there are. My solution is quite slow, because it creates a new object for every substring and sends method calls to each of them. Commented Jun 23, 2011 at 18:55
  • 2
    Fine answer, upvoted as such, but I challenge your definition of "easy". Sincerely, former Python guy now in ObjC-land ;-)
    – JK Laiho
    Commented May 31, 2012 at 9:17
  • 2
    You made me laugh with 'don't use complex solutions if there's an easy one'. So the easiest one is [toBeTrimmed stringByReplacingOccurrencesOfString:@" " withString:@""] no? I still upvote your answer but it's definitely the easiest Commented Jun 9, 2013 at 9:08
  • 2
    @MárioCarvalho The question asks how to remove excess whitespace, not all of it.
    – swilliams
    Commented Jul 1, 2013 at 19:42
53

Regex and NSCharacterSet is here to help you. This solution trims leading and trailing whitespace as well as multiple whitespaces.

NSString *original = @"    Hello      this  is a   long       string!   ";

NSString *squashed = [original stringByReplacingOccurrencesOfString:@"[ ]+"
                                                         withString:@" "
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, original.length)];

NSString *final = [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Logging final gives

"Hello this is a long string!"

Possible alternative regex patterns:

  • Replace only space: [ ]+
  • Replace space and tabs: [ \\t]+
  • Replace space, tabs and newlines: \\s+

Performance rundown

Ease of extension, performance, number lines of code and the number of objects created makes this solution appropriate.

2
  • 3
    hfossli's is the most elegant answer, in my book. Plus I just learned you can use regular expressions in stringByReplacingOccurrencesOfString:. Can't believe I didn't know that.
    – davidf2281
    Commented Aug 14, 2013 at 1:24
  • 1
    Awesome. Worked like a charm Commented May 27, 2015 at 10:29
41

Actually, there's a very simple solution to that:

NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)

(Source)

7
  • 29
    I think that this will eliminate only leading and trailing spaces, and eliminate all of them. it won't deal with "hello foo" Commented Sep 15, 2009 at 14:09
  • 2
    d*mn line endings and auto-format... it doesn't deal with "hello______foo" (assume _ -> " " because formatting comments is hard) Commented Sep 15, 2009 at 14:11
  • 32
    Why do you people vote for and answers which does not provide solution to the question? stringByTrimmingCharactersInSet does nor analyze the iside of the string but edges only. Answer by Georg Sholly is the perfect one.
    – Lukasz
    Commented Nov 13, 2011 at 21:45
  • 3
    Wasn't exactly an answer to the question, but it sure helped me. Thanks
    – daveMac
    Commented Dec 11, 2011 at 20:54
  • 1
    Excellent code for removing leading and trailing space at the same time.
    – user523234
    Commented Feb 12, 2012 at 16:27
13

With a regex, but without the need for any external framework:

NSString *theString = @"    Hello      this  is a   long       string!   ";

theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
                       options:NSRegularExpressionSearch
                       range:NSMakeRange(0, theString.length)];
2
  • You'd also then still need to trim the result, or you'll be padded with whitespace. This is probably the simplest answer, though.
    – lilbyrdie
    Commented Jun 23, 2011 at 15:28
  • 2
    the documentation for NSRegularExpressionSearch says that it only works with the rangeOfString:... methods
    – user102008
    Commented Jul 5, 2011 at 19:56
9

A one line solution:

NSString *whitespaceString = @" String with whitespaces ";

NSString *trimmedString = [whitespaceString
        stringByReplacingOccurrencesOfString:@" " withString:@""];
4
  • 2
    Helped me out :). Thanks for that!
    – thedom
    Commented Dec 20, 2010 at 18:06
  • 5
    While this is useful, it removes all whitespace. The OP basically wants whitespace compaction, e.g. a trim followed by reduction of consecutive whitespace to a single whitespace.
    – lilbyrdie
    Commented Jun 23, 2011 at 15:27
  • Another note, this solution does no deal with tabs or newlines or whitespace characters other than spaces.
    – cthulhu
    Commented Feb 8, 2012 at 10:33
  • 2
    This does not answer the OP, but instead removes all the spaces in the string, so you end up with @"Stringwithwhitespaces"
    – charles
    Commented Sep 17, 2012 at 15:10
6

This should do it...

NSString *s = @"this is    a  string    with lots  of     white space";
NSArray *comps = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSMutableArray *words = [NSMutableArray array];
for(NSString *comp in comps) {
  if([comp length] > 1)) {
    [words addObject:comp];
  }
}

NSString *result = [words componentsJoinedByString:@" "];
2
  • 1
    Does this actually work with the string 'a'? It's of length 1, as far as I can see, this solution will filter out all split words with size 0 and 1.
    – cthulhu
    Commented Feb 8, 2012 at 10:34
  • Yes that's the answer I was expecting. Thanks +1 Commented Dec 5, 2012 at 12:04
4

Another option for regex is RegexKitLite, which is very easy to embed in an iPhone project:

[theString stringByReplacingOccurencesOfRegex:@" +" withString:@" "];
0
3

Try This

NSString *theString = @"    Hello      this  is a   long       string!   ";

while ([theString rangeOfString:@"  "].location != NSNotFound) {
    theString = [theString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
}
3

Here's a snippet from an NSString extension, where "self" is the NSString instance. It can be used to collapse contiguous whitespace into a single space by passing in [NSCharacterSet whitespaceAndNewlineCharacterSet] and ' ' to the two arguments.

- (NSString *) stringCollapsingCharacterSet: (NSCharacterSet *) characterSet toCharacter: (unichar) ch {
int fullLength = [self length];
int length = 0;
unichar *newString = malloc(sizeof(unichar) * (fullLength + 1));

BOOL isInCharset = NO;
for (int i = 0; i < fullLength; i++) {
    unichar thisChar = [self characterAtIndex: i];

    if ([characterSet characterIsMember: thisChar]) {
        isInCharset = YES;
    }
    else {
        if (isInCharset) {
            newString[length++] = ch;
        }

        newString[length++] = thisChar;
        isInCharset = NO;
    }
}

newString[length] = '\0';

NSString *result = [NSString stringWithCharacters: newString length: length];

free(newString);

return result;
}
0
-1

Alternative solution: get yourself a copy of OgreKit (the Cocoa regular expressions library).

  • OgreKit (Japanese webpage -- code is in English)
  • OgreKit (Google autotranslation):

The whole function is then:

NSString *theStringTrimmed =
   [theString stringByTrimmingCharactersInSet:
        [NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression  *regex =
    [OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);

Short and sweet.

If you're after the fastest solution, a carefully constructed series of instructions using NSScanner would probably work best but that'd only be necessary if you plan to process huge (many megabytes) blocks of text.

2
  • Is there a reason to use OgreKit instead of RegExKitLite? regexkit.sourceforge.net It has a very similar replaceOccurrencesOfRegex call, and works on top of the existing RegEX libraries (not sure if Ogre is a whole RegEX engine or what) Commented Apr 18, 2009 at 4:42
  • I'm sure both will work. I haven't used regexkit but its a good suggestion to make. People should choose based on the underlying libraries: the PERL-compatible pcre (RegExKitLite) and the Ruby-compatible Oniguruma (OgreKit). Commented Apr 20, 2009 at 2:50
-1

according from @Mathieu Godart is best answer, but some line is missing , all answers just reduce space between words , but when if have tabs or have tab in place space , like this: " this is text \t , and\tTab between , so on " in three line code we will : the string we want reduce white spaces

NSString * str_aLine = @"    this is text \t , and\tTab between      , so on    ";
// replace tabs to space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
// reduce spaces to one space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@" +" withString:@" "
                                                    options:NSRegularExpressionSearch
                                                      range:NSMakeRange(0, str_aLine.length)];
// trim begin and end from white spaces
str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

the result is

"this is text , and Tab between , so on"

without replacing tab the resul will be:

"this is text    , and  Tab between , so on"
-1

You can also use a simple while argument. There is no RegEx magic in there, so maybe it is easier to understand and alter in the future:

while([yourNSStringObject replaceOccurrencesOfString:@"  "
                         withString:@" "
                         options:0
                         range:NSMakeRange(0, [yourNSStringObject length])] > 0);
1
  • 1
    Does not answer the question :) It does not remove leading and trailing whitespace.
    – hfossli
    Commented Jan 5, 2014 at 12:31
-1

Following two regular expressions would work depending on the requirements

  1. @" +" for matching white spaces and tabs
  2. @"\\s{2,}" for matching white spaces, tabs and line breaks

Then apply nsstring's instance method stringByReplacingOccurrencesOfString:withString:options:range: to replace them with a single white space.

e.g.

[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];

Note: I did not use 'RegexKitLite' library for the above functionality for iOS 5.x and above.

2
  • This solution doesn't remove leading and trailing whitespace as the OP asks for.
    – hfossli
    Commented Dec 3, 2014 at 8:22
  • @hfossli leading/trailing spaces can be removed by directly calling NSString's stringByTrimmingCharactersInSet: method with new/white line characterset. Above solution was to remove the redundant spaces independent of their location.
    – apalvai
    Commented Dec 12, 2014 at 22:49

Your Answer

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