I have a NSString
like this:
Hello
World
of
Twitter
Lets See this
>
I want to transform it to:
Hel
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.
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)));
Split the string into components and join them by space:
NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];
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:@" "];
I'm using
[...]
myString = [myString stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];
[...]
/Paul