Removing new line characters from NSString

I have an NSString :

 Hello World of Twitter Lets See this > 

I want to convert it to:

Hello World of Twitter Let's see this>

How can i do this? I am using Objective-C on the iPhone.

+46
string ios objective-c iphone
Nov 27 '09 at 10:02
source share
5 answers

Divide the line into components and connect them with a space:

 NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "]; 
+123
Nov 27 '09 at 10:05
source share


Splitting a string into components and reuniting with them is a very long way to do this. I also use the same method that Paul spoke about. You can replace any occurrences of a string. In addition to what Paul said, you can replace newline characters with such spaces:

 myString = [myString stringByReplacingOccurrencesOfString:@"\n" withString:@" "]; 
+79
Nov 27 '09 at 17:13
source share

I use

 [...] myString = [myString stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"]; [...] 

/ Paul

+8
Nov 27 '09 at 17:01
source share

My case also contains \r , including \n , [NSCharacterSet newlineCharacterSet] does not work, instead, using

 htmlContent = [htmlContent stringByReplacingOccurrencesOfString:@"[\r\n]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, htmlContent.length)]; 

solved my problem.

Btw, \\s will remove all spaces that are not expected.

+2
Jul 19 '16 at 8:11
source share

Providing Swift 3.0 @hallski version here:

 self.content = self.content.components(separatedBy: CharacterSet.newlines).joined(separator: " ") 

Providing Swift 3.0 @Kjuly version here (note that it replaces any number of newlines with only one \ n. I would rather not use a regular express if someone could tell me the best way):

 self.content = self.content.replacingOccurrences(of: "[\r\\n]+", with: "\n", options: .regularExpression, range: Range(uncheckedBounds: (lower: self.content.startIndex, upper: self.content.endIndex))); 
+2
Nov 05 '16 at 22:06
source share



All Articles