1

I am splitting a string into array at new line. The text comes from a server and can be created on multiple platforms. Have no issues with Unix text, however because of the new line definition issues (\n\r vs \n), the text is not split if it is sent from Windows-based server.

I am using this to find a regex expression for a new line and replace it with \n:

let stringRev = self.string.stringByReplacingOccurrencesOfString( "(\r\n|\r|\n)", withString: "\n", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)

let myArray = stringRev.componentsSeparatedByString("\n")

Is there a way to do it in Swift?

Many thanks!

3
  • are you getting an error? or whats the current output? ... Also instead of regex have you just tried self.string.stringByReplacingOccurrencesOfString("\r\n", withString: "\n", options: NSStringCompareOptions.LiteralSearch, range: nil) Commented Oct 22, 2015 at 22:43
  • Actually - just learned you do not need the optional parameters - .stringByReplacingOccurrencesOfString("\r\n", withString: "\n") Commented Oct 22, 2015 at 22:49
  • Depending on what I use ("\r\n" or "\r|), the string is not split either in Windows or on Mac. Just concatenates the new line with the previous. Therefore, I needed a regex to work with all platforms. Commented Oct 22, 2015 at 23:36

1 Answer 1

4

You can use String method enumerateLines:

let input = "Line 1\r\nLine 2\r\nLine3"
var result:[String] = []
input.enumerateLines { (line, _) -> () in
    result.append(line)
}

print(result)  // "["Line 1", "Line 2", "Line3"]\n

You can also use componentsSeparatedByCharactersInSet and use NSCharacterSet.newlineCharacterSet() to break up your lines

let input = "Line 1\rLine 2\rLine3"
let linesArray =  input.componentsSeparatedByCharactersInSet(.newlineCharacterSet())

linesArray  // ["Line 1", "Line 2", "Line3"]

If you are planning to use it somewhere else in your code you can create an extension:

extension String {
    var linesArray:[String] {
        var result:[String] = []
        enumerateLines { (line, _) -> () in
            result.append(line)
        }
        return result
    }
    var lines: [String] {
        return componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
    }
}

let input = "Line 1\nLine 2\nLine3"
let allLinesSample = input.linesArray  // ["Line 1", "Line 2", "Line3"]

let input2 = "Line 1\r\nLine 2\r\nLine3"
let allLinesSample2 = input2.linesArray  // ["Line 1", "Line 2", "Line3"]

let input3 = "Line 1\rLine 2\rLine3"
let allLinesSample3 = input3.lines  // ["Line 1", "Line 2", "Line3"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This is great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.