Reputation: 14527
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
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
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