Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

284
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda