假设我这里有一个字符串:
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.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 5.2的更新和最简单的方式
let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])
这张照片,
[“Bob”,“hit”,“a”,“ball”,“the”,“击球”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,“Hie”,“How”,“u”,“”]
但是,如果要过滤空字符串,
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})
输出
[“Bob”,“hit”,“a”,“ball”,“the”,“命中”,“ball”,“fly”,“far”,“after”,“it”,“was”,“hit”,“Hello”,”Hie“,”How“,”r“,”u“]
但请确保,Foundation已导入。
在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))
空白问题
一般来说,人们会一次又一次地重复这个问题和糟糕的解决方案。这是一个空间吗?“”以及“\n”、“\t”或一些您从未见过的unicode空白字符,在很大程度上是不可见的。虽然你可以逃脱
弱解决方案
import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")
如果你需要在现实中动摇你的控制,请观看WWDC视频中的字符串或日期。简而言之,让苹果解决这类平凡的任务几乎总是更好的。
稳健的解决方案:使用NSCharacterSet
IMHO,正确做到这一点的方法是使用NSCharacterSet,因为正如前面所述,您的空白可能不是您所期望的,并且Apple提供了一个空白字符集。要探索提供的各种字符集,请查看Apple的NSCharacterSet开发人员文档,然后,如果不符合您的需要,才可以扩充或构建新的字符集。
NSCharacterSet空白
返回包含Unicode常规中的字符的字符集Z类和字符表(U+0009)。
let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)
这是用于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 ")