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.
Edit: Forgetting import Foundation. If I import foundation it will work. But is there any way to do with extending String class? Thank you
Swift – Split a String by Character Separator To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.
To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.
Objective-C Language NSString Splitting If you need to split on a set of several different delimiters, use -[NSString componentsSeparatedByCharactersInSet:] . If you need to break a string into its individual characters, loop over the length of the string and convert each character into a new string.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With