Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
Split String into Array keeping delimiter/separator in Swift

Looking for an (elegant) solution for splitting a string and keeping the separator as item(s) in the array

example 1:

"hello world"

["hello", " ", "world"]

example 2:

" hello world"

[" ", "hello", " ", "world"]

thx.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Suppose you are splitting the string by a separator called separator, you can do the following:

let result = yourString.components(separatedBy:  separator) // first split
                        .flatMap { [$0, separator] } // add the separator after each split
                        .dropLast() // remove the last separator added
                        .filter { $0 != "" } // remove empty strings

For example:

let result = " Hello World ".components(separatedBy:  " ").flatMap { [$0, " "] }.dropLast().filter { $0 != "" }
print(result) // [" ", "Hello", " ", "World", " "]
over 4 years ago · Santiago Trujillo Report

0

For people who have a condition for their split, for example: splitting a camelCaseString based on uppercase condition:

extension Sequence {
    func splitIncludeDelimiter(whereSeparator shouldDelimit: (Element) throws -> Bool) rethrows -> [[Element]] {
        try self.reduce([[]]) { group, next in
            var group = group
            if try shouldDelimit(next) {
                group.append([next])
            } else {
                group[group.lastIdx].append(next)
            }
            return group
        }
    }
}

For example:

"iAmCamelCase".splitIncludeDelimiter(whereSeparator: \.isUppercase)
=>
["i", "Am", "Camel", "Case"]

(If you want the imp of isUppercase)

extension CharacterSet {
    static let uppercaseLetters = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
}

extension Unicode.Scalar {
    var isUppercase: Bool {
        CharacterSet.uppercaseLetters.contains(self)
    }
}
over 4 years ago · Santiago Trujillo Report

0

Just for fun, the Swift Algorithms package contains an algorithm called Intersperse

After adding the package and

import Algorithms

you can write

let string = "hello world"
let separator = " "

let result = Array(string
                     .components(separatedBy: separator)
                     .interspersed(with: separator))
print(result)

Your second example is barely correct, the result of splitting " hello world" by space is

["", "hello", "world"]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!