Swift Note

兴趣是最好的老师

Swift 字符串拆成数组

有蛮多方法的

单个分隔符

如果只需要用单个分隔符来拆分字符串的话,可以使用componentsSeparatedByString,比如使用半角逗号","来分割的话:

let someArray = string.componentsSeparatedByString(",")  

也可以用characters.split来实现:

let someArray = characters.split(",").map(String.init)  

characters.split方法返回的是 String.CharacterView对象,需要将其转换为String

let someArray = characters.split(",")  
let someStringItem = String(someArray[0])  

多分隔符

更多时候是需要用多个分隔符来进行分割,这时上面的方法就不能用了。

比如用全角和半角的逗号(,,)来分割:

就可以用

let separator = NSCharacterSet(charactersInString: ",,")  
var someArray = string.componentsSeparatedByCharactersInSet(separator)  

或者使用 enumerateSubstringsInRange

var someArray = [String]()  
string.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .BySentences) {  
    substring, substringRange, enclosingRange, stop in
    someArray.append(substring!)
}

enumerateSubstringsInRangeoptions 参数貌似只能用预设的:

struct NSStringEnumerationOptions : OptionSetType {  
    init(rawValue rawValue: UInt)
    static var ByLines: NSStringEnumerationOptions { get }
    static var ByParagraphs: NSStringEnumerationOptions { get }
    static var ByComposedCharacterSequences: NSStringEnumerationOptions { get }
    static var ByWords: NSStringEnumerationOptions { get }
    static var BySentences: NSStringEnumerationOptions { get }
    static var Reverse: NSStringEnumerationOptions { get }
    static var SubstringNotRequired: NSStringEnumerationOptions { get }
    static var Localized: NSStringEnumerationOptions { get }
}

神飞

没有什么能够阻挡,我对自由的向往