Peter Warbo
Peter Warbo

Reputation: 11700

Objective-C – Replace newline sequences with one space

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

Answers (4)

hfossli
hfossli

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:

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

Upvotes: 14

Sergey Kalinichenko
Sergey Kalinichenko

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:

  • First line splits by newline characters
  • Second line removes empty items inserted for multiple separators in a row
  • Third line joins the strings back using a single space as the new separator

Upvotes: 14

Mattias Wadman
Mattias Wadman

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

wattson12
wattson12

Reputation: 11174

Use a regular expression, something like "s/\n+/\w/" (a replace which will match 1 or more newline character and replace with a single white space)

this question has a link to a regex library, but there is NSRegularExpression available too

Upvotes: 0

Related Questions