Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,693 questions

57,001 answers

573 users

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
...