本文翻譯自: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 2In 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"