假设我这里有一个字符串:
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]
此外,有时用户可能没有姓氏。
当前回答
在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中将字符串拆分为数组的步骤。
赋值字符串基于@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)
非顶部:
对于搜索如何使用子字符串(而不是字符)拆分字符串的人来说,下面是一个有效的解决方案:
// TESTING
let str1 = "Hello user! What user's details? Here user rounded with space."
let a = str1.split(withSubstring: "user") // <-------------- HERE IS A SPLIT
print(a) // ["Hello ", "! What ", "\'s details? Here ", " rounded with space."]
// testing the result
var result = ""
for item in a {
if !result.isEmpty {
result += "user"
}
result += item
}
print(str1) // "Hello user! What user's details? Here user rounded with space."
print(result) // "Hello user! What user's details? Here user rounded with space."
print(result == str1) // true
/// Extension providing `split` and `substring` methods.
extension String {
/// Split given string with substring into array
/// - Parameters:
/// - string: the string
/// - substring: the substring to search
/// - Returns: array of components
func split(withSubstring substring: String) -> [String] {
var a = [String]()
var str = self
while let range = str.range(of: substring) {
let i = str.distance(from: str.startIndex, to: range.lowerBound)
let j = str.distance(from: str.startIndex, to: range.upperBound)
let left = str.substring(index: 0, length: i)
let right = str.substring(index: j, length: str.length - j)
a.append(left)
str = right
}
if !str.isEmpty {
a.append(str)
}
return a
}
/// the length of the string
public var length: Int {
return self.count
}
/// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
///
/// - parameter index: the start index
/// - parameter length: the length of the substring
///
/// - returns: the substring
public func substring(index: Int, length: Int) -> String {
if self.length <= index {
return ""
}
let leftIndex = self.index(self.startIndex, offsetBy: index)
if self.length <= index + length {
return String(self[leftIndex..<self.endIndex])
}
let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
return String(self[leftIndex..<rightIndex])
}
}
let fullName : String = "Steve.Jobs"
let fullNameArr : [String] = fullName.components(separatedBy: ".")
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
我发现了一个有趣的案例
方法1
var data:[String] = split( featureData ) { $0 == "\u{003B}" }
当我使用此命令从从服务器加载的数据中拆分一些符号时,它可以在模拟器中测试时拆分,并与测试设备同步,但不会在发布应用程序和Ad Hoc中拆分
我花了很多时间来跟踪这个错误,它可能会被某些Swift版本或iOS版本诅咒,或者两者都没有
这也与HTML代码无关,因为我尝试stringByRemovangPercentEncoding,但它仍然不起作用
2015年10月10日新增
在Swift 2.0中,此方法已更改为
var data:[String] = featureData.split {$0 == "\u{003B}"}
方法2
var data:[String] = featureData.componentsSeparatedByString("\u{003B}")
当我使用此命令时,它可以正确分割从服务器加载的相同数据
结论,我真的建议使用方法2
string.componentsSeparatedByString("")
斯威夫特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
}