假设我这里有一个字符串:
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]
此外,有时用户可能没有姓氏。
最简单的方法是使用组件SeparatedBy:
对于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]
对于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]
只需在fullName上调用componentsSeparatedByString方法
import Foundation
var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")
var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]
Swift 3更新+
import Foundation
let fullName = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")
let name = fullNameArr[0]
let surname = fullNameArr[1]
作为WMios答案的替代方案,您还可以使用componentsSeparatedByCharactersSet,这在分隔符(空格、逗号等)较多的情况下非常方便。
使用您的特定输入:
let separators = NSCharacterSet(charactersInString: " ")
var fullName: String = "First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)
// words contains ["First", "Last"]
使用多个分隔符:
let separators = NSCharacterSet(charactersInString: " ,")
var fullName: String = "Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)
// words contains ["Last", "First", "Middle"]
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
Swift 4或更高版本
如果您只需要正确设置人名格式,可以使用PersonNameComponentsFormater。
PersonNameComponentsFormater类提供本地化人名组成部分的表示通过PersonNameComponents对象。使用此类创建本地化当向用户显示人名信息时。
// 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."
}
编辑/更新:
Swift 5或更高版本
对于按非字母字符拆分字符串,我们可以使用新的Character属性isLetter:
let fullName = "First Last"
let components = fullName.split{ !$0.isLetter }
print(components) // "["First", "Last"]\n"
我发现了一个有趣的案例
方法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("")
这在Beta 5中再次发生了变化。哭泣!它现在是CollectionType上的一个方法
旧版本:
var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
新建:
var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}
苹果发行说明
或者没有闭包,你可以在Swift 2中这样做:
let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])
对于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]
空白问题
一般来说,人们会一次又一次地重复这个问题和糟糕的解决方案。这是一个空间吗?“”以及“\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)
let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]
Xcode 7.2(7C68)
根据Swift 2.2
您只需编写2行代码,就会得到拆分字符串。
let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[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", "--"]
斯威夫特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
}
大多数这些答案都假设输入包含一个空格,而不是空白,并且只有一个空格。如果你能安全地做出这样的假设,那么(来自bennett的)公认的答案是相当优雅的,也是我在可能的时候会采用的方法。
当我们无法做出这一假设时,一个更稳健的解决方案需要涵盖以下大多数答案没有考虑的情况:
制表符/换行符/空格(空白),包括重复出现的字符前导/尾随空格Apple/Linux(\n)和Windows(\r\n)换行符
为了涵盖这些情况,此解决方案使用正则表达式将所有空格(包括重复出现的字符和Windows换行符)转换为单个空格,然后修剪,然后拆分为单个空格:
斯威夫特3:
let searchInput = " First \r\n \n \t\t\tMiddle Last "
let searchTerms = searchInput
.replacingOccurrences(
of: "\\s+",
with: " ",
options: .regularExpression
)
.trimmingCharacters(in: .whitespaces)
.components(separatedBy: " ")
// searchTerms == ["First", "Middle", "Last"]
Xcode 8.0/Swift 3
let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")
var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last
漫长的道路:
var fullName: String = "First Last"
fullName += " " // this will help to see the last word
var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array
for Character in fullName.characters {
if Character == " " {
fullNameArr.append(newElement)
newElement = ""
} else {
newElement += "\(Character)"
}
}
var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last
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"]
我有一个场景,其中多个控制字符可以出现在我要拆分的字符串中。我只是让苹果处理这一部分,而不是维护一系列这些。
以下功能适用于iOS 10上的Swift 3.0.1:
let myArray = myString.components(separatedBy: .controlCharacters)
字符串处理在Swift中仍然是一个挑战,而且它一直在显著变化,从其他答案中可以看到。希望事情稳定下来,事情会变得更简单。这是在当前3.0版本的Swift中使用多个分隔符的方法。
斯威夫特3:
let chars = CharacterSet(charactersIn: ".,; -")
let split = phrase.components(separatedBy: chars)
// Or if the enums do what you want, these are preferred.
let chars2 = CharacterSet.alphaNumerics // .whitespaces, .punctuation, .capitalizedLetters etc
let split2 = phrase.components(separatedBy: chars2)
Swift 4使拆分字符变得更加容易,只需为字符串使用新的拆分函数即可。
例子:让s=“嗨,你好”让a=s.split(分隔符:“,”)打印(a)
现在您得到了一个带有“hi”和“hello”的数组。
斯威夫特4
let words = "these words will be elements in an array".components(separatedBy: " ")
我还没有找到能够处理3个或更多组件名称并支持较旧iOS版本的解决方案。
struct NameComponentsSplitter {
static func split(fullName: String) -> (String?, String?) {
guard !fullName.isEmpty else {
return (nil, nil)
}
let components = fullName.components(separatedBy: .whitespacesAndNewlines)
let lastName = components.last
let firstName = components.dropLast().joined(separator: " ")
return (firstName.isEmpty ? nil : firstName, lastName)
}
}
通过测试用例:
func testThatItHandlesTwoComponents() {
let (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Smith")
XCTAssertEqual(firstName, "John")
XCTAssertEqual(lastName, "Smith")
}
func testThatItHandlesMoreThanTwoComponents() {
var (firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Smith")
XCTAssertEqual(firstName, "John Clark")
XCTAssertEqual(lastName, "Smith")
(firstName, lastName) = NameComponentsSplitter.split(fullName: "John Clark Jr. Smith")
XCTAssertEqual(firstName, "John Clark Jr.")
XCTAssertEqual(lastName, "Smith")
}
func testThatItHandlesEmptyInput() {
let (firstName, lastName) = NameComponentsSplitter.split(fullName: "")
XCTAssertEqual(firstName, nil)
XCTAssertEqual(lastName, nil)
}
let fullName : String = "Steve.Jobs"
let fullNameArr : [String] = fullName.components(separatedBy: ".")
var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]
雨燕3
let line = "AAA BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
返回三个字符串AAA、BBB和CCC筛选出空字段处理多个空格和制表字符如果要处理新行,请将.whittespaces替换为.whittespace和新行
var fullName = "James Keagan Michael"
let first = fullName.components(separatedBy: " ").first?.isEmpty == false ? fullName.components(separatedBy: " ").first! : "John"
let last = fullName.components(separatedBy: " ").last?.isEmpty == false && fullName.components(separatedBy: " ").last != fullName.components(separatedBy: " ").first ? fullName.components(separatedBy: " ").last! : "Doe"
不允许使用相同的名字和姓氏如果全名无效,则取占位符值“John Doe”
在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)
假设您有一个名为“Hello World”的变量,如果您想将其拆分并存储为两个不同的变量,可以这样使用:
var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last
斯威夫特4
let string = "loremipsum.dolorsant.amet:"
let result = string.components(separatedBy: ".")
print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")
输出
loremipsum
dolorsant
amet:
total: 3
Swift 4、Xcode 10和iOS 12更新100%工作
let fullName = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullNameArr[1] //Last
有关更多信息,请参阅此处的Apple文档。
我在寻找loosy拆分,例如PHP的分解,其中空序列包含在结果数组中,这对我很有用:
"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)
输出:
["First", ""]
在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))
您可以使用此公共函数并添加任何要分隔的字符串
func separateByString(String wholeString: String, byChar char:String) -> [String] {
let resultArray = wholeString.components(separatedBy: char)
return resultArray
}
var fullName: String = "First Last"
let array = separateByString(String: fullName, byChar: " ")
var firstName: String = array[0]
var lastName: String = array[1]
print(firstName)
print(lastName)
这是用于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 ")
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已导入。
这直接提供了一个分割部分的数组
var fullNameArr = fullName.components(separatedBy:" ")
那么你可以这样使用,
var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]
只有拆分才是正确的答案,这里有两个以上空格的差异。
雨燕5
var temp = "Hello world ni hao"
let arr = temp.components(separatedBy: .whitespacesAndNewlines)
// ["Hello", "world", "", "", "", "", "ni", "hao"]
let arr2 = temp.components(separatedBy: " ")
// ["Hello", "world", "", "", "", "", "ni", "hao"]
let arr3 = temp.split(whereSeparator: {$0 == " "})
// ["Hello", "world", "ni", "hao"]
在解释Don Vaughn的答案时,我喜欢使用正则表达式。我很惊讶这只是Regex的第二个答案。然而,如果我们能用一个拆分方法而不是多个方法来解决这个问题,那就太好了。
我也受到了米特拉·辛加姆(Mithra Singam)的《答案》(Answer)的启发,排除了所有标点符号和空格。然而,不得不创建一个不允许的角色列表并没有引起我的共鸣。
\w-字母或数字符号的正则表达式。没有标点符号。
let foo = "(..# Hello,,(---- World ".split {
String($0).range(of: #"\w"#, options: .regularExpression) == nil
}
print(foo) // Prints "Hello World"
让我们假设你对Unicode不太满意。ASKII字母和数字怎么样?
let bar = "(..# Hello,,(---- World ".split {
!($0.isASCII && ($0.isLetter || $0.isNumber))
}
print(bar) // Prints "Hello World"
非顶部:
对于搜索如何使用子字符串(而不是字符)拆分字符串的人来说,下面是一个有效的解决方案:
// 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 = "First Last"
let components = fullName.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }
这将处理不同类型的一行中的多个空格(空格、制表符、换行符等),并且只返回一个两元素数组,您可以更改CharacterSet以包含更多您喜欢的字符,如果您想获得切割符,可以使用正则表达式解码器,这允许您编写正则表达式,该表达式可用于将字符串直接解码到实现解码协议的自己的类/结构中。对于像这样的东西来说,这是过度的,但如果您将其用作更复杂字符串的示例,则可能更有意义。
将字符串拆分为数组的简单方法
var fullName:String=“First Last”;var fullNameArr=fullName.componentsSeparatedByString(“”)var firstName:String=fullNameArr[0]var lastName:String=fullNameArr[1]