Reputation: 11700
How can I replace newline (\n) sequences with one space.
I.e the user has entered a double newline ("\n\n") I want that replaced with one space (" "). Or the user has entered triple newlines ("\n\n\n") I want that replaced with also one space (" ").
Upvotes: 11
Views: 6801
Reputation: 22962
3 times more performant than using componentsSeparatedByCharactersInSet
NSString *fixed = [original stringByReplacingOccurrencesOfString:@"\\n+"
withString:@" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
Possible alternative regex patterns:
[ ]+
[ \\t]+
\\s+
\\n+
Upvotes: 14
Reputation: 726499
Try this:
NSArray *split = [orig componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
split = [split filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
NSString *res = [split componentsJoinedByString:@" "];
This is how it works:
Upvotes: 14
Reputation: 11425
As wattson says you can do this with NSRegularExpression
but the code is quite verbose so if you want to do this at several places I suggestion you to do a helper method or even a NSString
category with method like -[NSString stringByReplacingMatchingPattern:withString:]
or something similar.
NSString *string = @"a\n\na";
NSLog(@"%@", [[NSRegularExpression regularExpressionWithPattern:@"\\n+"
options:0
error:NULL]
stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:@" "]);
Upvotes: 3