Removing new line characters from NSString

IosObjective CIphoneString

Ios Problem Overview


I have a NSString like this:

Hello 
World
of
Twitter
Lets See this
>

I want to transform it to:

> Hello World of Twitter Lets See this >

How can I do this? I'm using Objective-C on an iPhone.

Ios Solutions


Solution 1 - Ios

Split the string into components and join them by space:

NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];

Solution 2 - Ios


Splitting the string into components and rejoining them is a very long-winded way to do this. I too use the same method Paul mentioned. You can replace any string occurrences. Further to what Paul said you can replace new line characters with spaces like this:

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

Solution 3 - Ios

I'm using

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

/Paul

Solution 4 - Ios

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

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

solved my problem.

Btw, \\s will remove all white spaces, which is not expected.

Solution 5 - Ios

Providing a Swift 3.0 version of @hallski 's answer here:

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

Providing a Swift 3.0 version of @Kjuly 's answer here (Note it replaces any number of new lines with just one \n. I would prefer to not use regular express if someone can point me a better way):

self.content = self.content.replacingOccurrences(of: "[\r\\n]+", with: "\n", options: .regularExpression, range: Range(uncheckedBounds: (lower: self.content.startIndex, upper: self.content.endIndex)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiony ramesh raoView Question on Stackoverflow
Solution 1 - IoshallskiView Answer on Stackoverflow
Solution 2 - IosimnkView Answer on Stackoverflow
Solution 3 - IosPaul PeelenView Answer on Stackoverflow
Solution 4 - IosKjulyView Answer on Stackoverflow
Solution 5 - IosMichael ShangView Answer on Stackoverflow