0

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?

Ser Pounce
  • 14,196
  • 18
  • 84
  • 169
  • http://stackoverflow.com/questions/758212/collapse-sequences-of-white-space-into-a-single-character ? And using the `whitespaceAndNewlineCharacterSet` instead for the `NSCharacterSet`? – Larme May 21 '15 at 15:18
  • @Larme Yeah I think essentially that is what Matt had below. Wasn't able to find that question. Thanks for posting that. – Ser Pounce May 21 '15 at 16:43

2 Answers2

2

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

Community
  • 1
  • 1
l0gg3r
  • 8,864
  • 3
  • 26
  • 46
1

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)];
matt
  • 515,959
  • 87
  • 875
  • 1,141