Swift Version of Componentsseparatedbystring

Swift version of componentsSeparatedByString

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)

componentsSeparatedByString() Error in Swift 3

It looks like there is a components(separatedBy:) on String:

import Foundation

let words = "apple binary cat delta echo".components(separatedBy: " ")
print(words)

Sample Image

IBM Playground link:
http://swiftlang.ng.bluemix.net/#/repl/57868332b4e4e9971bf9f4e8

componentsSeparatedByString method in Swift

In xcode 6.1.1 componentsSeperatedByString method returns [AnyObject]. You have to cast it to [String] like so:

if let arr = urlContent.componentsSeparatedByString("<span class=\"Some  HTML class\">") as? [String] {
// arr is now [Sstring]
}

In xcode 6.3 beta this method returns [String] so cast is not needed.

componentsseparatedbystring by multiple separators in Swift

There is a method provided that lets you enumerate a string. You can do so by words or sentences or other options. No need for regular expressions.

let s = "Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."
var sentences = [String]()
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .BySentences) {
substring, substringRange, enclosingRange, stop in
sentences.append(substring!)
}
print(sentences)

The result is:

["Hi! ", "How are you? ", "I\'m fine. ", "It is 6 p.m. ", "Thank you! ", "That\'s it."]

Swift equivalent of Array.componentsJoinedByString?


Swift 3.0:

Similar to Swift 2.0, but API renaming has renamed joinWithSeparator to joined(separator:).

let joinedString = ["1", "2", "3", "4", "5"].joined(separator: ", ")

// joinedString: String = "1, 2, 3, 4, 5"

See Sequence.join(separator:) for more information.

Swift 2.0:

You can use the joinWithSeparator method on SequenceType to join an array of strings with a string separator.

let joinedString = ["1", "2", "3", "4", "5"].joinWithSeparator(", ")

// joinedString: String = "1, 2, 3, 4, 5"

See SequenceType.joinWithSeparator(_:) for more information.

Swift 1.0:

You can use the join standard library function on String to join an array of strings with a string.

let joinedString = ", ".join(["1", "2", "3", "4", "5"])

// joinedString: String = "1, 2, 3, 4, 5"

Or if you'd rather, you can use the global standard library function:

let joinedString = join(", ", ["1", "2", "3", "4", "5"])

// joinedString: String = "1, 2, 3, 4, 5"

component(separatedBy:) versus .split(separator: )

I have made sample test with following Code.

  var str = """
One of those refinements is to the String API, which has been made a lot easier to use (while also gaining power) in Swift 4. In past versions of Swift, the String API was often brought up as an example of how Swift sometimes goes too far in favoring correctness over ease of use, with its cumbersome way of handling characters and substrings. This week, let’s take a look at how it is to work with strings in Swift 4, and how we can take advantage of the new, improved API in various situations. Sometimes we have longer, static strings in our apps or scripts that span multiple lines. Before Swift 4, we had to do something like inline \n across the string, add an appendOnNewLine() method through an extension on String or - in the case of scripting - make multiple print() calls to add newlines to a long output. For example, here is how TestDrive’s printHelp() function (which is used to print usage instructions for the script) looks like in Swift 3 One of those refinements is to the String API, which has been made a lot easier to use (while also gaining power) in Swift 4. In past versions of Swift, the String API was often brought up as an example of how Swift sometimes goes too far in favoring correctness over ease of use, with its cumbersome way of handling characters and substrings. This week, let’s take a look at how it is to work with strings in Swift 4, and how we can take advantage of the new, improved API in various situations. Sometimes we have longer, static strings in our apps or scripts that span multiple lines. Before Swift 4, we had to do something like inline \n across the string, add an appendOnNewLine() method through an extension on String or - in the case of scripting - make multiple print() calls to add newlines to a long output. For example, here is how TestDrive’s printHelp() function (which is used to print usage instructions for the script) looks like in Swift 3
"""

var newString = String()

for _ in 1..<9999 {
newString.append(str)
}

var methodStart = Date()

_ = newString.components(separatedBy: " ")
print("Execution time Separated By: \(Date().timeIntervalSince(methodStart))")

methodStart = Date()
_ = newString.split(separator: " ")
print("Execution time Split By: \(Date().timeIntervalSince(methodStart))")

I run above code on iPhone6 , Here are the results

Execution time Separated By: 8.27463299036026
Execution time Split By: 4.06880903244019

Conclusion : split(separator:) is faster than components(separatedBy:).

componentsSeparatedByString - get component that is the string being split on

If instead of componentsSeparatedByString you do it using the split method from the standard library, you can use a stateful closure to do it in a fairly hacky way by remembering if the last element was a comma and then not splitting on two in a row:

let s = "a,b,c,,,1,2,3"

var lastWasComma = false
let array = split(s.characters) { (c: Character)->Bool in
if c == "," {
lastWasComma = !lastWasComma
}
else {
lastWasComma = false
}
return lastWasComma
}.map(String.init)

debugPrint(array)
// prints ["a", "b", "c", ",", "1", "2", "3"]

(this is for 2.0 - if you’re on 1.2, drop the .characters and the map from the end, since strings are directly sliceable before 2.0)

componentsSeparatedByString not working in swift

As per @wain commented, I have check for unicode value of "-" and it worked.

I have replaced this code

let currentPart : String = allparts[index]

let data = "\\U2013".dataUsingEncoding(NSUTF8StringEncoding)

let unicode = NSString(data: data!, encoding: NSNonLossyASCIIStringEncoding)

let timeParts = currentPart.componentsSeparatedByString(" \(unicode!) ")

Which is more complicated code to do small thing. So as per @Martin R suggest, the easy code to do this is

let currentPart : String = allparts[index]

let timeParts = currentPart.componentsSeparatedByString(" \u{2013} ")

Split a String into an array in Swift?

The Swift way is to use the global split function, like so:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

with Swift 2

In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).

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


Related Topics



Leave a reply



Submit