Objective-C – Replace newline sequences with one space

别来无恙 提交于 2019-11-27 06:04:11

问题


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 (" ").


回答1:


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



回答2:


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+



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/11360905/objective-c-replace-newline-sequences-with-one-space

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