ios - Swift 版本的 componentsSeparatedByString

标签 ios swift

我知道这是菜鸟问题,我真的在问之前四处搜索。但是我想知道的内容没有确切的答案。 我们如何在不使用 Objective C 的情况下将字符串拆分为数组?例如:

var str = "Today is so hot"
var arr = str.componentsSeparatedByString(" ")  // *
  • 我知道它不起作用,但我正在寻找这样的东西。我想用“”(或另一个字符/字符串)拆分字符串

想法:对我来说可能很好,做字符串类的扩展。但我不知道我该怎么做。

编辑:忘记导入基础。如果我导入基础,它将起作用。但是有什么办法可以扩展 String 类吗? 谢谢

最佳答案

如果你想用给定的字符分割一个字符串,那么你可以使用 内置 split() 方法,无需 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) 的参数顺序发生了变化,比较 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 的更新:请参阅 Stuart's answer .

Swift 3 更新:

let str = "Today is so hot"
let arr = str.characters.split(separator: " ").map(String.init)
print(arr)

关于ios - Swift 版本的 componentsSeparatedByString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226940/

相关文章:

iphone - iPhone 上的设置包值未正确链接

iphone - 在单元格中有 UITextView 的情况下无法选择 UITable 单元格

iOS: "Include of non-modular header"与 libxml

objective-c - 如何在 swift 中使用 USBmakebmRequestType

ios - 对许多对象执行相同的操作

iphone - 如何在 iphone 中创建具有 Marquee Effect 的动态多个 uiview

ios - 更新商店中的应用程序时的 SQLite 数据库

ios - 输出顺序在嵌套查询中变得不同,使用 Firebase 3,Swift

ios - UITableView使用willDisplay拉动刷新和分页

swift - UIView 未正确更改颜色值 SWIFT