Objective-C – Replace newline sequences with one space

匆匆过客 提交于 2019-11-29 06:28:25

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

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+

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:@" "]);
wattson12

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!