How to split a string into words in Swift

2 Answers

0 votes
import Foundation

func splitString(_ s: String, delims: String) -> [String] {
    let pattern: String = delims
    let regex: NSRegularExpression = try! NSRegularExpression(pattern: pattern)

    let range = NSRange(s.startIndex..<s.endIndex, in: s)
    let normalized: String = regex.stringByReplacingMatches(in: s, range: range, withTemplate: " ")

    let parts: [String] = normalized
        .components(separatedBy: " ")
        .filter { !$0.isEmpty }

    return parts
}

let s: String = "-c, c++.. c#:: -java ,php...python      swift"
let delims: String = "[ ,.:\\-!]+"

let tokens: [String] = splitString(s, delims: delims)

for t in tokens {
    print(t)
}



/*
run:

c
c++
c#
java
php
python
swift

*/

 



answered Aug 29 by avibootz
0 votes
import Foundation

func splitString(_ s: String, delims: String) -> [String] {
    let delimSet = CharacterSet(charactersIn: delims)

    let normalized = s.map { ch in
        delimSet.contains(ch.unicodeScalars.first!) ? " " : String(ch)
    }.joined()

    return normalized.split(separator: " ").map(String.init)
}

let s: String = "-c, c++.. c#:: -java ,php...python      swift!"
let delims: String = " ,.:\\-!"

let tokens: [String] = splitString(s, delims: delims)

for t in tokens {
    print(t)
}


/*
run:

c
c++
c#
java
php
python
swift

*/

 



answered Aug 29 by avibootz
...