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

var fullName: String = "First Last"

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

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

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

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


当前回答

字符串处理在Swift中仍然是一个挑战,而且它一直在显著变化,从其他答案中可以看到。希望事情稳定下来,事情会变得更简单。这是在当前3.0版本的Swift中使用多个分隔符的方法。

斯威夫特3:

let chars = CharacterSet(charactersIn: ".,; -")
let split = phrase.components(separatedBy: chars)

// Or if the enums do what you want, these are preferred. 
let chars2 = CharacterSet.alphaNumerics // .whitespaces, .punctuation, .capitalizedLetters etc
let split2 = phrase.components(separatedBy: chars2)

其他回答

只需在fullName上调用componentsSeparatedByString方法

import Foundation

var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")

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

Swift 3更新+

import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]

Xcode 8.0/Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

漫长的道路:

var fullName: String = "First Last"
fullName += " " // this will help to see the last word

var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array

for Character in fullName.characters {
    if Character == " " {
        fullNameArr.append(newElement)
        newElement = ""
    } else {
        newElement += "\(Character)"
    }
}


var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last

在解释Don Vaughn的答案时,我喜欢使用正则表达式。我很惊讶这只是Regex的第二个答案。然而,如果我们能用一个拆分方法而不是多个方法来解决这个问题,那就太好了。

我也受到了米特拉·辛加姆(Mithra Singam)的《答案》(Answer)的启发,排除了所有标点符号和空格。然而,不得不创建一个不允许的角色列表并没有引起我的共鸣。

\w-字母或数字符号的正则表达式。没有标点符号。

let foo = "(..#   Hello,,(---- World   ".split {
    String($0).range(of: #"\w"#, options: .regularExpression) == nil
}
print(foo) // Prints "Hello World"

让我们假设你对Unicode不太满意。ASKII字母和数字怎么样?

let bar = "(..#   Hello,,(---- World   ".split {
    !($0.isASCII && ($0.isLetter || $0.isNumber))
}
print(bar) // Prints "Hello World"

在Swift 4中将字符串拆分为数组的步骤。

赋值字符串基于@spling。

注意:variableName.components(separatedBy:“split关键字”)

let fullName: String = "First Last @ triggerd event of the session by session storage @ it can be divided by the event of the trigger."
let fullNameArr = fullName.components(separatedBy: "@")
print("split", fullNameArr)

这是用于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 ")