Ser Pounce
Ser Pounce

Reputation: 14527

Replace stretches of spaces and newlines with just a space in a string

I was wondering if there is a library or easy way that allows me to take an NSString and replace any stretch of '\n' and spaces that are strung together with just a single space? (included in this, I also just want to replace all occurrences of '\n' by itself with a space). So I'd want to take an NSString like this:

bla     bla  
    bla bla

and convert it to this:

bla bla bla bla

I've looked around and it seems the only it can be done is manually. Does anyone know if there is another way?

Upvotes: 0

Views: 260

Answers (2)

matt
matt

Reputation: 534950

As always in these situations, I am a huge fan of regular expressions. How did we ever get along without them? So I would call stringByReplacingOccurrencesOfString... with the options: including the regular expression specifier, and use a simple pattern expression that finds all stretches of whitespace (and replaces it with a single space).

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

Upvotes: 1

l0gg3r
l0gg3r

Reputation: 8954

Just separate string by \n and join it using spaces.

NSString *result = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];

This will remove new lines, to collapse sequence of whitespaces into single whitespace, use this

Upvotes: 2

Related Questions