本文翻譯自:Split a String into an array in Swift?
Say I have a string here: 說我在這裏有一個字符串:
var fullName: String = "First Last"
I want to split the string base on white space and assign the values to their respective variables 我想在空白處分割字符串並將值分配給它們各自的變量
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
Also, sometimes users might not have a last name. 同樣,有時用戶可能沒有姓氏。
#1樓
參考:https://stackoom.com/question/1jk7J/在Swift中將字符串拆分成數組
#2樓
The easiest method to do this is by using componentsSeparatedBy: 最簡單的方法是使用componentsSeparatedBy:
For Swift 2: 對於Swift 2:
import Foundation
let fullName : String = "First Last";
let fullNameArr : [String] = fullName.componentsSeparatedByString(" ")
// And then to access the individual words:
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
For Swift 3: 對於Swift 3:
import Foundation
let fullName : String = "First Last"
let fullNameArr : [String] = fullName.components(separatedBy: " ")
// And then to access the individual words:
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
#3樓
Just call componentsSeparatedByString
method on your fullName
只需在您的fullName
上調用componentsSeparatedByString
方法
import Foundation
var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")
var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]
Update for Swift 3+ Swift 3+更新
import Foundation
let fullName = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")
let name = fullNameArr[0]
let surname = fullNameArr[1]
#4樓
As an alternative to WMios's answer, you can also use componentsSeparatedByCharactersInSet
, which can be handy in the case you have more separators (blank space, comma, etc.). 作爲WMios答案的替代方法,您還可以使用componentsSeparatedByCharactersInSet
,如果您有更多的分隔符(空格,逗號等),則可以使用該componentsSeparatedByCharactersInSet
。
With your specific input: 用您的特定輸入:
let separators = NSCharacterSet(charactersInString: " ")
var fullName: String = "First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)
// words contains ["First", "Last"]
Using multiple separators: 使用多個分隔符:
let separators = NSCharacterSet(charactersInString: " ,")
var fullName: String = "Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)
// words contains ["Last", "First", "Middle"]
#5樓
The Swift way is to use the global split
function, like so: Swift的方法是使用全局split
功能,如下所示:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
with Swift 2 與Swift 2
In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. 在Swift 2中,由於引入了內部CharacterView類型,對split的使用變得更加複雜。 This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters
property to access a CharacterView type representation of a String instance. 這意味着String不再採用SequenceType或CollectionType協議,而必須使用.characters
屬性訪問String實例的CharacterView類型表示。 (Note: CharacterView does adopt SequenceType and CollectionType protocols). (注意:CharacterView確實採用SequenceType和CollectionType協議)。
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)
fullNameArr[0] // First
fullNameArr[1] // Last
#6樓
Swift 4 or later Swift 4或更高版本
If you just need to properly format a person name, you can use PersonNameComponentsFormatter . 如果只需要正確格式化人名,則可以使用PersonNameComponentsFormatter 。
The PersonNameComponentsFormatter class provides localized representations of the components of a person's name, as represented by a PersonNameComponents object. PersonNameComponentsFormatter類提供人名組成部分的本地化表示,如PersonNameComponents對象所表示。 Use this class to create localized names when displaying person name information to the user. 在向用戶顯示人員姓名信息時,使用此類創建本地化的姓名。
// iOS (9.0 and later), macOS (10.11 and later), tvOS (9.0 and later), watchOS (2.0 and later)
let nameFormatter = PersonNameComponentsFormatter()
let name = "Mr. Steven Paul Jobs Jr."
// personNameComponents requires iOS (10.0 and later)
if let nameComps = nameFormatter.personNameComponents(from: name) {
nameComps.namePrefix // Mr.
nameComps.givenName // Steven
nameComps.middleName // Paul
nameComps.familyName // Jobs
nameComps.nameSuffix // Jr.
// It can also be configured to format your names
// Default (same as medium), short, long or abbreviated
nameFormatter.style = .default
nameFormatter.string(from: nameComps) // "Steven Jobs"
nameFormatter.style = .short
nameFormatter.string(from: nameComps) // "Steven"
nameFormatter.style = .long
nameFormatter.string(from: nameComps) // "Mr. Steven Paul Jobs jr."
nameFormatter.style = .abbreviated
nameFormatter.string(from: nameComps) // SJ
// It can also be use to return an attributed string using annotatedString method
nameFormatter.style = .long
nameFormatter.annotatedString(from: nameComps) // "Mr. Steven Paul Jobs jr."
}
edit/update: 編輯/更新:
Swift 5 or later Swift 5或更高版本
For just splitting a string by non letter characters we can use the new Character property isLetter
: 僅用非字母字符分割字符串,我們可以使用新的Character屬性isLetter
:
let fullName = "First Last"
let components = fullName.split{ !$0.isLetter }
print(components) // "["First", "Last"]\n"