关于ios:在Swift中将一个String拆分成一个数组?

Split a String into an array in Swift?

假设我这里有一根绳子:

1
var fullName: String ="First Last"

我想基于空白分割字符串并将值赋给它们各自的变量

1
2
3
4
var fullNameArr = // something like: fullName.explode("")

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

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


只需在你的fullName上调用componentsSeparatedByString方法

1
2
3
4
5
6
7
import Foundation

var fullName: String ="First Last"
let fullNameArr = fullName.componentsSeparatedByString("")

var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]

Swift 3的更新+

1
2
3
4
5
6
7
import Foundation

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

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


快速的方法是使用全球split功能,如:

1
2
3
4
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类型,split的使用变得更加复杂。这意味着字符串不再采用SequenceType或CollectionType协议,而必须使用.characters属性来访问字符串实例的CharacterView类型表示。(注:CharacterView采用SequenceType和CollectionType协议)。

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
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]

斯威夫特3:

1
2
3
4
5
6
7
8
9
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]


Swift Dev.4.0(2017年5月24日)

swift 4(beta)中的新功能split

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

输出:

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

访问值:

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

Xcode 8.1/Swift 3.0.1

下面是使用数组的多个分隔符的方法。

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

输出:

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


作为wmios答案的替代方案,您也可以使用componentsSeparatedByCharactersInSet,这在您有更多分隔符(空格、逗号等)的情况下非常方便。

根据您的具体输入:

1
2
3
4
5
let separators = NSCharacterSet(charactersInString:"")
var fullName: String ="First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["First","Last"]

使用多个分隔符:

1
2
3
4
5
let separators = NSCharacterSet(charactersInString:" ,")
var fullName: String ="Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["Last","First","Middle"]


斯威夫特4

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


xcode 9 swift 4或xcode 8.2.1?SWIFT 3.0.2

如果您只需要正确格式化人名,可以使用人名组件格式。

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 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."
}

enter image description here

编辑/更新:

Swift 5或更高版本

对于仅用非字母字符拆分字符串,我们可以使用新的字符属性isLetter

1
2
3
4
5
let fullName ="First Last"

let components = fullName.split{ !$0.isLetter }
print(components)  //"["First","Last"]
"


空白区问题

一般来说,人们反复地重新发明这个问题和坏的解决方案。这是一个空间吗?"还有,关于"n"、"t"或一些您从未见过的Unicode空白字符呢,这在很大程度上是因为它是不可见的。当你能摆脱

弱解

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

如果你需要改变你对现实的把握,那就去看一部WWDC的关于弦或日期的视频吧。简而言之,让苹果解决这类平凡的任务几乎总是更好的。

强大的解决方案:使用nscharacterset

正确的方法是,imho,使用NSCharacterSet,因为正如前面所述,您的空白可能不是您期望的,而且苹果提供了空白字符集。要了解提供的各种字符集,请查看Apple的nscharacterset开发人员文档,然后,只有在那时,如果不符合您的需要,才扩充或构建一个新的字符集。

非字符集空白

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

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


在Swift 4.2和Xcode 10中

1
2
//This is your str
let str ="This is my String" //Here replace with your string

选项1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

1
2
3
4
5
6
7
8
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

1
2
let arr = str.split {$0 ==""}
print(arr)

选项4

1
2
3
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!"]"

通过苹果文档…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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))


Swift 4使拆分字符更加容易,只需对字符串使用新的拆分函数即可。

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

现在你有了一个数组,上面有"嗨"和"你好"。


斯威夫特3

1
2
let line ="AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • 返回三个字符串AAABBBCCC
  • 筛选出空字段
  • 处理多个空格和制表符
  • 如果你想处理新的线路,那么用.whitespacesAndNewlines替换.whitespaces

Xcode 8.0/银行代码3

1
2
3
4
5
let fullName ="First Last"
var fullNameArr = fullName.components(separatedBy:"")

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

漫长的道路:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

我发现了一个有趣的案例

方法1

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

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

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

这也与HTML代码无关,因为我试图通过删除百分比编码来字符串化,但它仍然不起作用。

2015年10月10日增补

在Swift 2.0中,此方法已更改为

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

方法2

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

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

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

1
string.componentsSeparatedByString("")


我有一个场景,在我要拆分的字符串中可以存在多个控制字符。我并没有维护一系列这些,而是让苹果来处理这一部分。

以下内容适用于iOS 10上的Swift 3.0.1:

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


Swift 4、Xcode 10和iOS 12 100%工作更新

1
2
3
4
let fullName ="First Last"    
let fullNameArr = fullName.components(separatedBy:"")
let firstName = fullNameArr[0] //First
let lastName = fullnameArr[1] //Last

有关更多信息,请参阅此处的苹果文档。


这些答案中的大多数假设输入包含一个空格,而不是空白,并且只有一个空格。如果你能安全地做出这样的假设,那么(贝内特的)公认的答案是相当优雅的,而且我会尽可能采用这种方法。

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

  • 制表符/换行符/空格(空格),包括循环字符
  • 前导/尾随空格
  • apple/linux(
    和windows(

    换行符)

要解决这些问题,此解决方案使用regex将所有空白(包括重复出现的和Windows换行符)转换为单个空格、修剪,然后按单个空格拆分:

斯威夫特3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let searchInput ="  First

 
 \t\t\tMiddle    Last"
let searchTerms = searchInput
    .replacingOccurrences(
        of:"\\s+",
        with:"",
        options: .regularExpression
    )
    .trimmingCharacters(in: .whitespaces)
    .components(separatedBy:"")

// searchTerms == ["First","Middle","Last"]

或者不关闭,您可以在swift 2中执行此操作:

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

希望能帮上忙

swift 4:将字符串拆分为一个数组。步骤1:分配字符串。第2步:基于@spliting。注意:variablename.components(以"split关键字"分隔)

1
2
3
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)

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

xcode 7.2(7c68)代码


斯威夫特4

1
2
3
4
5
6
7
8
let string ="loremipsum.dolorsant.amet:"

let result = string.components(separatedBy:".")

print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")

产量

1
2
3
4
loremipsum
dolorsant
amet:
total: 3

斯威夫特2.2添加了错误处理和大写字符串:

1
2
3
4
5
6
7
8
9
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
}

假设您有一个名为"hello world"的变量,如果要将其拆分并存储为两个不同的变量,可以这样使用:

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

这里有一个我刚刚构建的算法,它将由任何Character从数组中拆分一个String,如果有任何希望保留具有拆分字符的子字符串,可以将swallow参数设置为true

Xcode 7.3-Swift 2.2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
            }
        }
    }
}

例子:

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

对于Swift 2,xcode 7.1:

1
2
3
4
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]


这在测试版5中又发生了变化。WEEE!它现在是CollectionType上的一个方法

旧的:

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

新的:

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

苹果发行说明


字符串处理仍然是Swift中的一个挑战,并且它一直在显著地变化,从其他答案可以看出。希望事情能稳定下来,事情会变得简单。这是使用具有多个分隔符字符的当前3.0版swift执行此操作的方法。

斯威夫特3:

1
2
3
4
5
6
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)

我在寻找疯狂的分裂,比如php的explode,其中空序列包含在生成的数组中,这对我很有用:

1
"First".split(separator:"", maxSplits: 1, omittingEmptySubsequences: false)

输出:

1
["First",""]

根据Swift 2.2

只需编写两行代码,就可以得到拆分字符串。

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

享受。:)


我还没有找到能够处理包含3个或更多组件的名称并支持旧版iOS的解决方案。

1
2
3
4
5
6
7
8
9
10
11
12
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)
    }
}

通过的测试用例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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)
}

Swift 5及以上

1
2
let fullString ="Last First Middle"
let fullNameArr = fullString.components(separatedBy:"")

1
2
3
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"

您可以使用这个公共函数并添加任何要分隔的字符串

1
2
3
4
5
6
7
8
9
10
11
12
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的字符串和csv文件,地址:20181206 1610

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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:"

").map{ $0.components(separatedBy:";") }
           for line in parsedCSV!
            {
                dataArray.append(line)
           }
        }
        catch let jsonErr {
            print("
   Error read CSV file:
", jsonErr)
        }

            print("
 MohNada 20181206 1610 - The final result is \(dataArray)  
")