把一个字符串分割成一个数组

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.

转载于:https://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array

weixin_41568110
七度&光 What do you call the technology to separate the string like "thisisatest" into "This is a test"? Any idea how to do that?
大约 3 年之前 回复
csdnceshi63
elliott.david Also, sometimes last names have spaces in them, as in "Daphne du Maurier" or "Charles de Lint"
大约 3 年之前 回复
csdnceshi74
7*4 If you are only splitting by one character, using fullName.utf8.split( <utf-8 character code> ) works as well (replace .utf8 with .utf16 for UTF-16). For example, splitting on + could be done using fullName.utf8.split(43)
4 年多之前 回复
csdnceshi67
bug^君 Hi, i dont have my Mac to check. But you can try 'fullName.componentsSeparatedByString(string:" ")' Dont copy and paste, use the autocompletefunction, so you get the right function.
大约 6 年之前 回复

30个回答

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

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

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 
weixin_41568208
北城已荒凉 Good Job , swift 4 Just Copy
大约 2 年之前 回复
csdnceshi79
python小菜 Downvoted until you update for swift 3. Just copy Chen's answer below.
接近 4 年之前 回复
csdnceshi76
斗士狗 Can you add explanation to your Syntax usage? What is $0 == " "?
大约 4 年之前 回复
csdnceshi69
YaoRaoLov How about editing out the old stuff and just showing the current answer. People who need a history lesson can check the edit history.
4 年多之前 回复
weixin_41568183
零零乙 Jeez!!!! APPLE! make up your mind!
4 年多之前 回复
csdnceshi59
ℙℕℤℝ wow, true, like 20x
4 年多之前 回复
csdnceshi56
lrony* lol all the iterations of Swift 2...
4 年多之前 回复
csdnceshi80
胖鸭 Anyone know how to split with more than 1 character? e.g. ". "
接近 5 年之前 回复
csdnceshi75
衫裤跑路 Using XCode 7.2 I got an error and I think @LeoDabus answer is more Swift.
接近 5 年之前 回复
csdnceshi78
程序go How can I split on "; " It only seems to allow one character for split?
接近 5 年之前 回复
csdnceshi72
谁还没个明天 The method for Xcode 7.0 no longer works in Xcode 7.1.
接近 5 年之前 回复
csdnceshi72
谁还没个明天 Geez, can't they make a .split() function like in Python already?
接近 5 年之前 回复
csdnceshi61
derek5. Answer need to be updated with comment from @skagedal because otherwise you have CharacterView instead of string but question was about string.
接近 5 年之前 回复
csdnceshi50
三生石@ for Swift 2: Xcode 7, fullNameArr[0] and fullNameArr[1] returns characterview
接近 5 年之前 回复
csdnceshi64
游.程 Correct code for Xcode 7.0 is let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init). Tried to edit, but it got rejected.
大约 5 年之前 回复
weixin_41568131
10.24 This answer doesn't wirk anymore as of Xcode7 beta5, see answers below
大约 5 年之前 回复
csdnceshi52
妄徒之命 then you could use split("a,b;c,d") {$0 == "," || $0 == ";"} or split("a,b;c,d") {contains(",;", $0)}
5 年多之前 回复
csdnceshi78
程序go If I want to use either "," or ";" as split characters, how can I modify your code?
5 年多之前 回复
csdnceshi62
csdnceshi62 Could you say why this solution is preferred over the componentsSeparatedByString approach ? Regards
5 年多之前 回复
weixin_41568184
叼花硬汉 Just remember that you still need to use the old componentsSeparatedByString() method if your separator is anything longer than a single character. And as cool as it would be to say let (firstName, lastName) = split(fullName) {$0 == ' '}, that doesn't work, sadly.
5 年多之前 回复
csdnceshi65
larry*wei As of Xcode 6.2b3 split can be used as split("a:b::c:", {$0 == ":"}, maxSplit: Int.max, allowEmptySlices: false).
5 年多之前 回复
csdnceshi74
7*4 In my tests, componentsSeparatedByString is usually significantly faster, especially when dealing with strings that require splitting into many pieces. But for the example listed by the OP, either should suffice.
接近 6 年之前 回复

The easiest method to do this is by using componentsSeparatedBy:

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

For 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]
csdnceshi50
三生石@ there are two functions: componentsSeparatedByString and componentsSeparatedByCharactersInSet
大约 5 年之前 回复
csdnceshi50
三生石@ consider .componentsSeparatedByCharactersInSet(.whitespaceAndNewlineCharacterSet())
5 年多之前 回复
csdnceshi54
hurriedly% Is this documented anywhere, Maury? What if I need to split on something other than a single character?
5 年多之前 回复

Just call componentsSeparatedByString method on your fullName

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+

import Foundation

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

let name    = fullNameArr[0]
let surname = fullNameArr[1]
csdnceshi66
必承其重 | 欲带皇冠 Is there a way to split using regex? I tried to do string.components(separatedBy: regex, options: .regularExpression) but I got an error.
3 年多之前 回复
csdnceshi67
bug^君 Using Swift 3 and XCode 8.2, I did not need to import Foundation.
3 年多之前 回复
weixin_41568184
叼花硬汉 It apparently requires Foundation to work, which is no longer available in Swift 2.2.1 on Linux.
4 年多之前 回复
csdnceshi69
YaoRaoLov Array subscript doesn't return optionals. var lastName: String? = fullNameArr[1] will not work.
4 年多之前 回复
csdnceshi78
程序go this may be 1000x better than the accepted answer... nicely done
4 年多之前 回复
csdnceshi58
Didn"t forge This works exactly as expected (i.e. fullNameArr is an [String]) in Xcode 7.2.
4 年多之前 回复
csdnceshi70
笑故挽风 It didn't work in the REPL until I imported Foundation.
接近 5 年之前 回复
csdnceshi64
游.程 this doesn't work in Swift 2: Xcode 7
接近 5 年之前 回复
csdnceshi60
℡Wang Yan This answer works in Xcode 7 beta 4 and Swift 2.0. Xcode now auto-completes Foundation methods on Swift String objects without type casting to an NSString, which is not the case in Xcode 6.4 with Swift 1.2.
大约 5 年之前 回复
weixin_41568134
MAO-EYE This answer does not work starting from Swift 1.2.
大约 5 年之前 回复
csdnceshi59
ℙℕℤℝ Is there an advantage to the accepted answer over this one?
大约 5 年之前 回复
weixin_41568131
10.24 I agree that this should be the accepted answer - much cleaner and simpler answer.
5 年多之前 回复
csdnceshi62
csdnceshi62 Which is no longer the case in Swift 1.2, in which Apple no longer converts Swift's String into NSString automagically.
5 年多之前 回复
weixin_41568208
北城已荒凉 Be noted that this is actually an underlying NSString (Swift automatically swaps them when importing Foundation).
5 年多之前 回复
weixin_41568174
from.. This answer is much more elegant than the accepted one. Programmers from Taiwan are awesome :D
5 年多之前 回复

For 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]
csdnceshi56
lrony* Any specific reason this was downvoted? Seems to work for me as well in Xcode 7.1.
接近 5 年之前 回复

I found an Interesting case, that

method 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

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

addition 10/10/2015

in Swift 2.0 this method has been changed to

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

method 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

string.componentsSeparatedByString("")
weixin_41568174
from.. I'd say this is close to "not an answer" status, in that it's mostly commentary on existing answers. But it is pointing out something important.
大约 5 年之前 回复

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

Old:

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

New:

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

Apples Release Notes

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.

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

Swift Dev. 4.0 (May 24, 2017)

A new function split in 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

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"]
csdnceshi78
程序go Any multi-character splits in Swift 4+?
大约 2 年之前 回复
weixin_41568184
叼花硬汉 Attention (Swift 4): If you have a string like let a="a,,b,c" and you use a.split(separator: ",") you get an array like ["a", "b", c"] by default. This can be changed using omittingEmptySubsequences: false which is true by default.
大约 3 年之前 回复
csdnceshi57
perhaps? Make sure to add import Foundation to the class you're using this in. #SavedYouFiveMinutes
3 年多之前 回复

Swift 3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • Returns three strings AAA, BBB and CCC
  • Filters out empty fields
  • Handles multiple spaces and tabulation characters
  • If you want to handle new lines, then replace .whitespaces with .whitespacesAndNewlines
let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]

Xcode 7.2 (7C68)

共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问