Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 361
Peter Warbo Avatar asked Jul 06 '12 10:07

Peter Warbo


Video Answer


1 Answers

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
like image 130
Sergey Kalinichenko Avatar answered Sep 22 '22 02:09

Sergey Kalinichenko