假设我这里有一个字符串:

var fullName: String = "First Last"

我想在空白处拆分字符串,并将值分配给它们各自的变量

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

此外,有时用户可能没有姓氏。


当前回答

Swift 5.2的更新和最简单的方式

let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"

let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])

这张照片,

[“Bob”,“hit”,“a”,“ball”,“the”,“击球”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,“Hie”,“How”,“u”,“”]

但是,如果要过滤空字符串,

let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})

输出

[“Bob”,“hit”,“a”,“ball”,“the”,“命中”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,”Hie“,”How“,”r“,”u“]

但请确保,Foundation已导入。

其他回答

最简单的解决方案是

let fullName = "First Last"

let components = fullName.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }

这将处理不同类型的一行中的多个空格(空格、制表符、换行符等),并且只返回一个两元素数组,您可以更改CharacterSet以包含更多您喜欢的字符,如果您想获得切割符,可以使用正则表达式解码器,这允许您编写正则表达式,该表达式可用于将字符串直接解码到实现解码协议的自己的类/结构中。对于像这样的东西来说,这是过度的,但如果您将其用作更复杂字符串的示例,则可能更有意义。

这里是我刚刚构建的一个算法,它将通过数组中的任何字符分割字符串,如果有任何希望保留具有分割字符的子字符串,可以将swall参数设置为true。

Xcode 7.3-Swift 2.2:

extension String {

    func splitBy(characters: [Character], swallow: Bool = false) -> [String] {

        var substring = ""
        var array = [String]()
        var index = 0

        for character in self.characters {

            if let lastCharacter = substring.characters.last {

                // swallow same characters
                if lastCharacter == character {

                    substring.append(character)

                } else {

                    var shouldSplit = false

                    // check if we need to split already
                    for splitCharacter in characters {
                        // slit if the last character is from split characters or the current one
                        if character == splitCharacter || lastCharacter == splitCharacter {

                            shouldSplit = true
                            break
                        }
                    }

                    if shouldSplit {

                        array.append(substring)
                        substring = String(character)

                    } else /* swallow characters that do not equal any of the split characters */ {

                        substring.append(character)
                    }
                }
            } else /* should be the first iteration */ {

                substring.append(character)
            }

            index += 1

            // add last substring to the array
            if index == self.characters.count {

                array.append(substring)
            }
        }

        return array.filter {

            if swallow {

                return true

            } else {

                for splitCharacter in characters {

                    if $0.characters.contains(splitCharacter) {

                        return false
                    }
                }
                return true
            }
        }
    }
}

例子:

"test text".splitBy([" "]) // ["test", "text"]
"test++text--".splitBy(["+", "-"], swallow: true) // ["test", "++" "text", "--"]

斯威夫特2.2添加了错误处理和大写字符串:

func setFullName(fullName: String) {
    var fullNameComponents = fullName.componentsSeparatedByString(" ")

    self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
    self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""

    self.fname = self.fname!.capitalizedString
    self.sname = self.sname!.capitalizedString
}
let fullName : String = "Steve.Jobs"
let fullNameArr : [String] = fullName.components(separatedBy: ".")

var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]

这是用于swift 4.2在20181206 1610的字符串和CSV文件

var dataArray : [[String]] = []
 let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
        let url = URL(fileURLWithPath: path!)
        do {
            let data = try Data(contentsOf: url) 
            let content = String(data: data, encoding: .utf8)
            let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
           for line in parsedCSV!
            {
                dataArray.append(line)
           }
        }
        catch let jsonErr {
            print("\n   Error read CSV file: \n ", jsonErr)
        }

            print("\n MohNada 20181206 1610 - The final result is \(dataArray)  \n ")