斯威夫特:字符串分割到数组在新行 - 基于Windows的文本 [英] Swift: Split string into array at new line - Windows-based text

查看:141
本文介绍了斯威夫特:字符串分割到数组在新行 - 基于Windows的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将字符串分割为在新的线阵列。文本来自一个服务器,并且可以在多种平台上被创建。与Unix的文字没有问题,但由于一些新线的定义问题(\\ n \\ r VS \\ n)时,文本不如果是从基于Windows的服务器发送的分割。

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.

我用这找到一个新行正则表达式的前pression和\\ n替换为:

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?

非常感谢!

推荐答案

您可以使用字符串方法enumerateLines:

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

您也可以使用componentsSeparatedByCharactersInSet和使用
NSCharacterSet.newlineCharacterSet()分手台词

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"]

如果你计划在$ C $其他地方使用它c可以创建扩展:

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"]

这篇关于斯威夫特:字符串分割到数组在新行 - 基于Windows的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆