Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

ios - Swift version of componentsSeparatedByString

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(" ")  // *
  • I know it doesnt work but i am looking for like that. I want to split string with " " (or another char/string)

Idea:It might be very good for me, making extension of string class. But i dont know how i do that.

Edit: Forgetting import Foundation. If I import foundation it will work. But is there any way to do with extending String class? Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to split a string by a given character then you can use the built-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]

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]

Update for Swift 2: See Stuart's answer.

Update for Swift 3:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...