Removing new line characters from NSString

前端 未结 5 1706
我寻月下人不归
我寻月下人不归 2020-12-03 00:55

I have a NSString like this:

Hello 
World
of
Twitter
Lets See this
>

I want to transform it to:

Hel

相关标签:
5条回答
  • 2020-12-03 00:57

    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.

    0 讨论(0)
  • 2020-12-03 01:08

    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)));
    
    0 讨论(0)
  • 2020-12-03 01:11

    Split the string into components and join them by space:

    NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];
    
    0 讨论(0)
  • 2020-12-03 01:13


    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:@" "];
    
    0 讨论(0)
  • 2020-12-03 01:19

    I'm using

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

    /Paul

    0 讨论(0)
提交回复
热议问题