Swift:将字符串分割为数组

时间:2023-01-16 21:31:17

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.

此外,有时用户可能没有姓。

26 个解决方案

#1


685  

The Swift way is to use the global split function, like so:

快速的方法是使用全局分割函数,如下所示:

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

斯威夫特2

In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. 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. (Note: CharacterView does adopt SequenceType and CollectionType protocols).

在Swift 2中,由于引入了内部字符视图类型,分割的使用变得有点复杂。这意味着字符串不再使用SequenceType或CollectionType协议,而必须使用.characters属性来访问字符串实例的字符视图类型表示。(注意:characters view确实采用了顺序类型和集合类型协议)。

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 

#2


790  

Just call componentsSeparatedByString method on your fullName

只需在您的全名上调用componentsseparation bystring方法

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+

更新迅速3 +

import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]

#3


134  

The easiest method to do this is by using componentsSeparatedBy:

最简单的方法是使用由:

For Swift 2:

为迅速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:

为迅速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]

#4


81  

Swift Dev. 4.0 (May 24, 2017)

快速发展。4.0(2017年5月24日)

A new function split in Swift 4 (Beta).

一个新的函数在Swift 4 (Beta)中分裂。

import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)

Output:

输出:

["Hello", "Swift", "4", "2017"]

Accessing values:

访问值:

print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017

Xcode 8.1 / Swift 3.0.1

Xcode 8.1 / Swift 3.0.1

Here is the way multiple delimiters with array.

这是使用数组的多个分隔符的方式。

import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)

Output:

输出:

["12", "37", "2", "5"]

#5


45  

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,如果您有更多的分隔符(空白空间、逗号等),这将非常方便。

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"]

#6


39  

Swift 4

斯威夫特4

let words = "these words will be elements in an array".components(separatedBy: " ")

#7


32  

Xcode 9 Swift 4 or Xcode 8.2.1 • Swift 3.0.2

Xcode 9 Swift 4或Xcode 8.2.1•Swift 3.0.2

If you just need to properly format a person name, you can use PersonNameComponentsFormatter.

如果您只需要正确地格式化一个person名称,您可以使用PersonNameComponentsFormatter。

The PersonNameComponentsFormatter class provides localized representations of the components of a person’s name, as represented by a PersonNameComponents object. Use this class to create localized names when displaying person name information to the user.

PersonNameComponentsFormatter类提供了人名的组件的本地化表示,如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.givenName    // Steven
    nameComps.middleName   // Paul
    nameComps.familyName   // Jobs
    nameComps.nameSuffix   // Jr.
    nameComps.namePrefix   // Mr.

    // It can also be convufgured 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:将字符串分割为数组

#8


22  

The whitespace issue

Generally, people reinvent this problem and bad solutions over and over. Is this a space? " " and what about "\n", "\t" or some unicode whitespace character that you've never seen, in no small part because it is invisible. While you can get away with

通常,人们会反复地重复这个问题和糟糕的解决方案。这是一个空间吗?还有“\n”、“\t”或一些你从未见过的unicode空格字符,在很大程度上是因为它是不可见的。而你可以侥幸逃脱

A weak solution

import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

If you ever need to shake your grip on reality watch a WWDC video on strings or dates. In short, it is almost always better to allow Apple to solve this kind of mundane task.

如果你需要改变你对现实的控制,观看一个关于字符串或日期的WWDC视频。简而言之,让苹果解决这类平凡的任务几乎总是更好的。

Robust Solution: Use NSCharacterSet

The way to do this correctly, IMHO, is to use NSCharacterSet since as stated earlier your whitespace might not be what you expect and Apple has provided a whitespace character set. To explore the various provided character sets check out Apple's NSCharacterSet developer documentation and then, only then, augment or construct a new character set if it doesn't fit your needs.

方法正确,恕我直言,是使用NSCharacterSet因为如前所述空格可能不是你希望和苹果公司提供了一个空白字符集。探索提供的各种字符集看看苹果的NSCharacterSet developer文档然后,只有这样,扩大或建立一个新的字符集如果它不适合你的需要。

NSCharacterSet whitespaces

Returns a character set containing the characters in Unicode General Category Zs and CHARACTER TABULATION (U+0009).

返回包含Unicode通用类别Zs和字符表格(U+0009)中的字符的字符集。

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)

#9


13  

Swift 3

斯威夫特3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • Returns three strings AAA, BBB and CCC
  • 返回三个字符串AAA, BBB和CCC
  • Filters out empty fields
  • 过滤掉空字段
  • Handles multiple spaces and tabulation characters
  • 处理多个空格和表格字符
  • If you want to handle new lines, then replace .whitespaces with .whitespacesAndNewlines
  • 如果您想处理新的行,那么将.whitespaces替换为. whitespacesesandnewlines

#10


12  

Swift 4 makes it much easier to split characters, just use the new split function for Strings.

Swift 4可以更容易地分割字符,只需对字符串使用新的分割函数。

Example: let s = "hi, hello" let a = s.split(separator: ",") print(a)

例:让s =“嗨,你好”让a = s。分割(分隔符:",")打印(a)

Now you got an array with 'hi' and ' hello'.

现在你有了一个带有“hi”和“hello”的数组。

#11


11  

Xcode 8.0 / Swift 3

Xcode 8.0 / Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

Long Way:

长方式:

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

#12


8  

I found an Interesting case, that

我发现了一个有趣的例子

method 1

方法1

var data:[String] = split( featureData ) { $0 == "\u{003B}" }

When I used this command to split some symbol from the data that loaded from server, it can split while test in simulator and sync with test device, but it won't split in publish app, and Ad Hoc

当我使用这个命令从服务器加载的数据中分离一些符号时,它可以在模拟器中进行测试并与测试设备同步,但是它不会在发布应用中分离,而且是特别的

It take me a lot of time to track this error, It might cursed from some Swift Version, or some iOS Version or neither

我花了很多时间来跟踪这个错误,它可能会被某个Swift版本或某个iOS版本所诅咒,或者两者都不是

It's not about the HTML code also, since I try to stringByRemovingPercentEncoding and it's still not work

这也不是HTML代码的问题,因为我尝试了stringbyremovingpercent编码,但它仍然不起作用

addition 10/10/2015

除了10/10/2015

in Swift 2.0 this method has been changed to

在Swift 2.0中,这个方法被更改为

var data:[String] = featureData.split {$0 == "\u{003B}"}

method 2

方法2

var data:[String] = featureData.componentsSeparatedByString("\u{003B}")

When I used this command, it can split the same data that load from server correctly

当我使用这个命令时,它可以正确地从服务器上加载相同的数据


Conclusion, I really suggest to use the method 2

结论:我真的建议使用方法2

string.componentsSeparatedByString("")

#13


7  

Most of these answers assume the input contains a space - not whitespace, and a single space at that. If you can safely make that assumption, then the accepted answer (from bennett) is quite elegant and also the method I'll be going with when I can.

这些答案中的大多数都假设输入包含一个空格——而不是空格,并且只有一个空格。如果你可以安全地做这个假设,那么可以接受的答案(来自bennett)是相当优雅的,当我可以的时候,我也会使用这个方法。

When we can't make that assumption, a more robust solution needs to cover the following siutations that most answers here don't consider:

当我们不能做出这样的假设时,一个更可靠的解决方案需要涵盖以下大多数答案都没有考虑到的问题:

  • tabs/newlines/spaces (whitespace), including recurring characters
  • 制表符/换行符/空格(空格),包括重复出现的字符
  • leading/trailing whitespace
  • 领先/落后于空白
  • Apple/Linux (\n) and Windows (\r\n) newline characters
  • 苹果/Linux (\n)和Windows (\r\n)换行字符

To cover these cases this solution uses regex to convert all whitespace (including recurring and Windows newline characters) to a single space, trims, then splits by a single space:

为了涵盖这些情况,本解决方案使用regex将所有空格(包括循环出现的和Windows换行字符)转换为单个空格,进行修剪,然后再分割为单个空格:

Swift 3:

斯威夫特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"]

#14


6  

Or without closures you can do just this in Swift 2:

或者没有闭包,你可以在Swift 2中这样做:

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])

#15


6  

I had a scenario where multiple control characters can be present in the string I want to split. Rather than maintain an array of these, I just let Apple handle that part.

我有一个场景,在我想要分割的字符串中可以显示多个控制字符。而不是维护这些数组,我只是让苹果处理那个部分。

The following works with Swift 3.0.1 on iOS 10:

iOS 10的Swift 3.0.1如下:

let myArray = myString.components(separatedBy: .controlCharacters)

#16


2  

let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]

Xcode 7.2 (7C68)

Xcode 7.2(7 c68)

#17


2  

Swift 2.2 Error Handling & capitalizedString Added :

Swift 2.2错误处理& capitalizedString添加:

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
}

#18


2  

Hope this is helpfull

希望这是经验

Swift 4: Split a String into an array. Step 1: assign string. step 2: based on @ spliting. Note: variableName.components(separatedBy: "split keyword")

Swift 4:将字符串分割为数组。步骤1:指定字符串。步骤2:基于@ spliting。注意:variableName.components(separatedBy:“分裂的关键字”)

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)

#19


2  

Let's say you have a variable named "Hello World" and if you want to split it and store it into two different variables you can use like this:

假设你有一个名为“Hello World”的变量,如果你想将它分割成两个不同的变量,你可以这样使用:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last

#20


1  

This has Changed again in Beta 5. Weee! It's now a method on CollectionType

在Beta 5中,情况又发生了变化。确立!它现在是一种集合类型的方法。

Old:

旧:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}

New:

新:

var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}

Apples Release Notes

苹果发布说明

#21


1  

For swift 2, XCode 7.1:

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]

#22


1  

As per Swift 2.2

2.2每迅速

You just write 2 line code and you will get the split string.

你只需要写两行代码就可以得到分割字符串。

let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[1]) 

Enjoy. :)

享受。:)

#23


1  

Here is an algorithm I just build, which will split a String by any Character from the array and if there is any desire to keep the substrings with splitted characters one could set the swallow parameter to true.

这是我刚刚构建的一个算法,它将根据数组中的任何字符分割一个字符串,如果有人希望将子字符串保留为分割字符,那么可以将swallow参数设置为true。

Xcode 7.3 - Swift 2.2:

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
            }
        }
    }
}

Example:

例子:

"test text".splitBy([" "]) // ["test", "text"]
"test++text--".splitBy(["+", "-"], swallow: true) // ["test", "++" "text", "--"]

#24


1  

String handling is still a challenge in Swift and it keeps changing significantly, as you can see from other answers. Hopefully things settle down and it gets simpler. This is the way to do it with the current 3.0 version of Swift with multiple separator characters.

字符串处理在Swift中仍然是一个挑战,并且它一直在显著地变化,您可以从其他答案中看到。希望事情安定下来,变得更简单。这是使用当前3.0版本的Swift实现多分隔符的方法。

Swift 3:

斯威夫特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)

#25


0  

I haven't found the solution that would handle names with 3 or more components and support older iOS versions.

我还没有找到能够处理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)
    }
}

Passed test cases:

通过测试用例:

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)
}

#26


0  

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"
  • Disallow same first and last name
  • 禁止使用相同的姓和名
  • If a fullname is invalid, take placeholder value "John Doe"
  • 如果全称无效,取占位符值“John Doe”

#1


685  

The Swift way is to use the global split function, like so:

快速的方法是使用全局分割函数,如下所示:

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

斯威夫特2

In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. 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. (Note: CharacterView does adopt SequenceType and CollectionType protocols).

在Swift 2中,由于引入了内部字符视图类型,分割的使用变得有点复杂。这意味着字符串不再使用SequenceType或CollectionType协议,而必须使用.characters属性来访问字符串实例的字符视图类型表示。(注意:characters view确实采用了顺序类型和集合类型协议)。

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 

#2


790  

Just call componentsSeparatedByString method on your fullName

只需在您的全名上调用componentsseparation bystring方法

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+

更新迅速3 +

import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]

#3


134  

The easiest method to do this is by using componentsSeparatedBy:

最简单的方法是使用由:

For Swift 2:

为迅速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:

为迅速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]

#4


81  

Swift Dev. 4.0 (May 24, 2017)

快速发展。4.0(2017年5月24日)

A new function split in Swift 4 (Beta).

一个新的函数在Swift 4 (Beta)中分裂。

import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)

Output:

输出:

["Hello", "Swift", "4", "2017"]

Accessing values:

访问值:

print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017

Xcode 8.1 / Swift 3.0.1

Xcode 8.1 / Swift 3.0.1

Here is the way multiple delimiters with array.

这是使用数组的多个分隔符的方式。

import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)

Output:

输出:

["12", "37", "2", "5"]

#5


45  

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,如果您有更多的分隔符(空白空间、逗号等),这将非常方便。

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"]

#6


39  

Swift 4

斯威夫特4

let words = "these words will be elements in an array".components(separatedBy: " ")

#7


32  

Xcode 9 Swift 4 or Xcode 8.2.1 • Swift 3.0.2

Xcode 9 Swift 4或Xcode 8.2.1•Swift 3.0.2

If you just need to properly format a person name, you can use PersonNameComponentsFormatter.

如果您只需要正确地格式化一个person名称,您可以使用PersonNameComponentsFormatter。

The PersonNameComponentsFormatter class provides localized representations of the components of a person’s name, as represented by a PersonNameComponents object. Use this class to create localized names when displaying person name information to the user.

PersonNameComponentsFormatter类提供了人名的组件的本地化表示,如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.givenName    // Steven
    nameComps.middleName   // Paul
    nameComps.familyName   // Jobs
    nameComps.nameSuffix   // Jr.
    nameComps.namePrefix   // Mr.

    // It can also be convufgured 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:将字符串分割为数组

#8


22  

The whitespace issue

Generally, people reinvent this problem and bad solutions over and over. Is this a space? " " and what about "\n", "\t" or some unicode whitespace character that you've never seen, in no small part because it is invisible. While you can get away with

通常,人们会反复地重复这个问题和糟糕的解决方案。这是一个空间吗?还有“\n”、“\t”或一些你从未见过的unicode空格字符,在很大程度上是因为它是不可见的。而你可以侥幸逃脱

A weak solution

import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

If you ever need to shake your grip on reality watch a WWDC video on strings or dates. In short, it is almost always better to allow Apple to solve this kind of mundane task.

如果你需要改变你对现实的控制,观看一个关于字符串或日期的WWDC视频。简而言之,让苹果解决这类平凡的任务几乎总是更好的。

Robust Solution: Use NSCharacterSet

The way to do this correctly, IMHO, is to use NSCharacterSet since as stated earlier your whitespace might not be what you expect and Apple has provided a whitespace character set. To explore the various provided character sets check out Apple's NSCharacterSet developer documentation and then, only then, augment or construct a new character set if it doesn't fit your needs.

方法正确,恕我直言,是使用NSCharacterSet因为如前所述空格可能不是你希望和苹果公司提供了一个空白字符集。探索提供的各种字符集看看苹果的NSCharacterSet developer文档然后,只有这样,扩大或建立一个新的字符集如果它不适合你的需要。

NSCharacterSet whitespaces

Returns a character set containing the characters in Unicode General Category Zs and CHARACTER TABULATION (U+0009).

返回包含Unicode通用类别Zs和字符表格(U+0009)中的字符的字符集。

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)

#9


13  

Swift 3

斯威夫特3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • Returns three strings AAA, BBB and CCC
  • 返回三个字符串AAA, BBB和CCC
  • Filters out empty fields
  • 过滤掉空字段
  • Handles multiple spaces and tabulation characters
  • 处理多个空格和表格字符
  • If you want to handle new lines, then replace .whitespaces with .whitespacesAndNewlines
  • 如果您想处理新的行,那么将.whitespaces替换为. whitespacesesandnewlines

#10


12  

Swift 4 makes it much easier to split characters, just use the new split function for Strings.

Swift 4可以更容易地分割字符,只需对字符串使用新的分割函数。

Example: let s = "hi, hello" let a = s.split(separator: ",") print(a)

例:让s =“嗨,你好”让a = s。分割(分隔符:",")打印(a)

Now you got an array with 'hi' and ' hello'.

现在你有了一个带有“hi”和“hello”的数组。

#11


11  

Xcode 8.0 / Swift 3

Xcode 8.0 / Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

Long Way:

长方式:

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

#12


8  

I found an Interesting case, that

我发现了一个有趣的例子

method 1

方法1

var data:[String] = split( featureData ) { $0 == "\u{003B}" }

When I used this command to split some symbol from the data that loaded from server, it can split while test in simulator and sync with test device, but it won't split in publish app, and Ad Hoc

当我使用这个命令从服务器加载的数据中分离一些符号时,它可以在模拟器中进行测试并与测试设备同步,但是它不会在发布应用中分离,而且是特别的

It take me a lot of time to track this error, It might cursed from some Swift Version, or some iOS Version or neither

我花了很多时间来跟踪这个错误,它可能会被某个Swift版本或某个iOS版本所诅咒,或者两者都不是

It's not about the HTML code also, since I try to stringByRemovingPercentEncoding and it's still not work

这也不是HTML代码的问题,因为我尝试了stringbyremovingpercent编码,但它仍然不起作用

addition 10/10/2015

除了10/10/2015

in Swift 2.0 this method has been changed to

在Swift 2.0中,这个方法被更改为

var data:[String] = featureData.split {$0 == "\u{003B}"}

method 2

方法2

var data:[String] = featureData.componentsSeparatedByString("\u{003B}")

When I used this command, it can split the same data that load from server correctly

当我使用这个命令时,它可以正确地从服务器上加载相同的数据


Conclusion, I really suggest to use the method 2

结论:我真的建议使用方法2

string.componentsSeparatedByString("")

#13


7  

Most of these answers assume the input contains a space - not whitespace, and a single space at that. If you can safely make that assumption, then the accepted answer (from bennett) is quite elegant and also the method I'll be going with when I can.

这些答案中的大多数都假设输入包含一个空格——而不是空格,并且只有一个空格。如果你可以安全地做这个假设,那么可以接受的答案(来自bennett)是相当优雅的,当我可以的时候,我也会使用这个方法。

When we can't make that assumption, a more robust solution needs to cover the following siutations that most answers here don't consider:

当我们不能做出这样的假设时,一个更可靠的解决方案需要涵盖以下大多数答案都没有考虑到的问题:

  • tabs/newlines/spaces (whitespace), including recurring characters
  • 制表符/换行符/空格(空格),包括重复出现的字符
  • leading/trailing whitespace
  • 领先/落后于空白
  • Apple/Linux (\n) and Windows (\r\n) newline characters
  • 苹果/Linux (\n)和Windows (\r\n)换行字符

To cover these cases this solution uses regex to convert all whitespace (including recurring and Windows newline characters) to a single space, trims, then splits by a single space:

为了涵盖这些情况,本解决方案使用regex将所有空格(包括循环出现的和Windows换行字符)转换为单个空格,进行修剪,然后再分割为单个空格:

Swift 3:

斯威夫特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"]

#14


6  

Or without closures you can do just this in Swift 2:

或者没有闭包,你可以在Swift 2中这样做:

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])

#15


6  

I had a scenario where multiple control characters can be present in the string I want to split. Rather than maintain an array of these, I just let Apple handle that part.

我有一个场景,在我想要分割的字符串中可以显示多个控制字符。而不是维护这些数组,我只是让苹果处理那个部分。

The following works with Swift 3.0.1 on iOS 10:

iOS 10的Swift 3.0.1如下:

let myArray = myString.components(separatedBy: .controlCharacters)

#16


2  

let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]

Xcode 7.2 (7C68)

Xcode 7.2(7 c68)

#17


2  

Swift 2.2 Error Handling & capitalizedString Added :

Swift 2.2错误处理& capitalizedString添加:

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
}

#18


2  

Hope this is helpfull

希望这是经验

Swift 4: Split a String into an array. Step 1: assign string. step 2: based on @ spliting. Note: variableName.components(separatedBy: "split keyword")

Swift 4:将字符串分割为数组。步骤1:指定字符串。步骤2:基于@ spliting。注意:variableName.components(separatedBy:“分裂的关键字”)

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)

#19


2  

Let's say you have a variable named "Hello World" and if you want to split it and store it into two different variables you can use like this:

假设你有一个名为“Hello World”的变量,如果你想将它分割成两个不同的变量,你可以这样使用:

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last

#20


1  

This has Changed again in Beta 5. Weee! It's now a method on CollectionType

在Beta 5中,情况又发生了变化。确立!它现在是一种集合类型的方法。

Old:

旧:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}

New:

新:

var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}

Apples Release Notes

苹果发布说明

#21


1  

For swift 2, XCode 7.1:

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]

#22


1  

As per Swift 2.2

2.2每迅速

You just write 2 line code and you will get the split string.

你只需要写两行代码就可以得到分割字符串。

let fullName = "FirstName LastName"
var splitedFullName = fullName.componentsSeparatedByString(" ")
print(splitedFullName[0])
print(splitedFullName[1]) 

Enjoy. :)

享受。:)

#23


1  

Here is an algorithm I just build, which will split a String by any Character from the array and if there is any desire to keep the substrings with splitted characters one could set the swallow parameter to true.

这是我刚刚构建的一个算法,它将根据数组中的任何字符分割一个字符串,如果有人希望将子字符串保留为分割字符,那么可以将swallow参数设置为true。

Xcode 7.3 - Swift 2.2:

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
            }
        }
    }
}

Example:

例子:

"test text".splitBy([" "]) // ["test", "text"]
"test++text--".splitBy(["+", "-"], swallow: true) // ["test", "++" "text", "--"]

#24


1  

String handling is still a challenge in Swift and it keeps changing significantly, as you can see from other answers. Hopefully things settle down and it gets simpler. This is the way to do it with the current 3.0 version of Swift with multiple separator characters.

字符串处理在Swift中仍然是一个挑战,并且它一直在显著地变化,您可以从其他答案中看到。希望事情安定下来,变得更简单。这是使用当前3.0版本的Swift实现多分隔符的方法。

Swift 3:

斯威夫特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)

#25


0  

I haven't found the solution that would handle names with 3 or more components and support older iOS versions.

我还没有找到能够处理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)
    }
}

Passed test cases:

通过测试用例:

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)
}

#26


0  

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"
  • Disallow same first and last name
  • 禁止使用相同的姓和名
  • If a fullname is invalid, take placeholder value "John Doe"
  • 如果全称无效,取占位符值“John Doe”