问题描述
我知道它的noob问题,我真的在搜索之前搜索。但对于我想知道的内容并没有确切的答案。
如何在不使用Objective C的情况下将字符串拆分为数组?例如:
I know its noob question, i really search around before ask. But there is not exact answer of what i want to know. How we split string into the array without using Objective C? For example:
var str = "Today is so hot"
var arr = str.componentsSeparatedByString(" ") // *
- 我知道它不起作用但我正在寻找像那。我想用(或其他字符/字符串)拆分字符串
想法:这对我来说可能非常好,进行扩展字符串类。但我不知道我是怎么做到的。
Idea:It might be very good for me, making extension of string class. But i dont know how i do that.
编辑:忘记导入基础。如果我导入基础它将工作。但有没有办法扩展String类?
谢谢
Forgetting import Foundation. If I import foundation it will work. But is there any way to do with extending String class?Thank you
推荐答案
如果你想按给定的字符分割字符串那么你可以使用
内置的 split()
方法,而不需要基金会:
If you want to split a string by a given character then you can use thebuilt-in split()
method, without needing Foundation:
let str = "Today is so hot"
let arr = split(str, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
println(arr) // [Today, is, so, hot]
Swift 1.2的更新:使用Swift 1.2(Xcode 6.3)更改参数的顺序,比较:
Update for Swift 1.2: The order of the parameters changed with Swift 1.2 (Xcode 6.3), compare split now complains about missing "isSeparator":
let str = "Today is so hot"
let arr = split(str, maxSplit: Int.max, allowEmptySlices: false, isSeparator: { $0 == " "} )
println(arr) // [Today, is, so, hot]
Swift 2的更新:参见。
Swift 3的更新:
let str = "Today is so hot"
let arr = str.characters.split(separator: " ").map(String.init)
print(arr)
这篇关于Swift版本的componentsSeparatedByString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!