假设我这里有一个字符串:
var fullName: String = "First Last"
我想在空白处拆分字符串,并将值分配给它们各自的变量
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
此外,有时用户可能没有姓氏。
假设我这里有一个字符串:
var fullName: String = "First Last"
我想在空白处拆分字符串,并将值分配给它们各自的变量
var fullNameArr = // something like: fullName.explode(" ")
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
此外,有时用户可能没有姓氏。
当前回答
这里是我刚刚构建的一个算法,它将通过数组中的任何字符分割字符串,如果有任何希望保留具有分割字符的子字符串,可以将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", "--"]
其他回答
对于swift 2,XCode 7.1:
let complete_string:String = "Hello world"
let string_arr = complete_string.characters.split {$0 == " "}.map(String.init)
let hello:String = string_arr[0]
let world:String = string_arr[1]
Swift Dev.4.0(2017年5月24日)
Swift 4(Beta版)中拆分了一个新功能。
import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)
输出:
["Hello", "Swift", "4", "2017"]
访问值:
print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017
Xcode 8.1/Swift 3.0.1
这是多个分隔符与数组的方式。
import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)
输出:
["12", "37", "2", "5"]
在Swift 4.2和Xcode 10中
//This is your str
let str = "This is my String" //Here replace with your string
选项1
let items = str.components(separatedBy: " ")//Here replase space with your value and the result is Array.
//Direct single line of code
//let items = "This is my String".components(separatedBy: " ")
let str1 = items[0]
let str2 = items[1]
let str3 = items[2]
let str4 = items[3]
//OutPut
print(items.count)
print(str1)
print(str2)
print(str3)
print(str4)
print(items.first!)
print(items.last!)
选项2
let items = str.split(separator: " ")
let str1 = String(items.first!)
let str2 = String(items.last!)
//Output
print(items.count)
print(items)
print(str1)
print(str2)
选项3
let arr = str.split {$0 == " "}
print(arr)
选项4
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
通过Apple文档。。。。
let line = "BLANCHE: I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
print(line.split(separator: " ", maxSplits: 1))//This can split your string into 2 parts
// Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
print(line.split(separator: " ", maxSplits: 2))//This can split your string into 3 parts
print(line.split(separator: " ", omittingEmptySubsequences: false))//array contains empty strings where spaces were repeated.
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
print(line.split(separator: " ", omittingEmptySubsequences: true))//array not contains empty strings where spaces were repeated.
print(line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: false))
print(line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true))
这里是我刚刚构建的一个算法,它将通过数组中的任何字符分割字符串,如果有任何希望保留具有分割字符的子字符串,可以将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", "--"]
Swift的方法是使用全局拆分函数,如下所示:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
使用Swift 2
在Swift 2中,由于引入了内部CharacterView类型,拆分的使用变得有点复杂。这意味着String不再采用SequenceType或CollectionType协议,您必须改为使用.characts属性来访问String实例的CharacterView类型表示。(注意: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