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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to split a string on multiple multi‑character delimiters (and keep them) in Swift

1 Answer

0 votes
import Foundation

func splitAndKeep(_ text: String, delims: Set<Character>) -> [String] {
    guard !text.isEmpty else { return [] }

    let chars = Array(text)
    var result: [String] = []
    var start = 0

    for i in 1..<chars.count {
        let prev = chars[i - 1]
        let curr = chars[i]

        let prevIsDelim = delims.contains(prev)
        let currIsDelim = delims.contains(curr)

        let shouldSplit =
            (prevIsDelim != currIsDelim) ||              // text ↔ delim
            (prevIsDelim && currIsDelim && prev != curr) // delim type changed

        if shouldSplit {
            result.append(String(chars[start..<i]))
            start = i
        }
    }

    // Add final segment
    result.append(String(chars[start...]))

    return result
}

let s = "aa==bbb---cccc++++ddddd"
let delimiters: Set<Character> = ["=", "-", "+"]

print(splitAndKeep(s, delims: delimiters))



/*
run:

["aa", "==", "bbb", "---", "cccc", "++++", "ddddd"]

*/

 



answered Mar 10 by avibootz

Related questions

...