user3043098 user3043098 - 1 year ago 83
Swift Question

Split String in Swift by their capital letters

I want to split an simple String by their capital letters into an array. It should look something like this:

let teststring = "NaCuHHe"

and the result should be:

["Na", "Cu", "H", "He"]

I tried the following:

func capitalLetters(s: String) -> [Character] {
return s.characters.filter { ("A"..."Z").contains($0) }

I searched trough the documentation and other websites but i did not find any helpful things. Im at the end. I don't know what to do more hence im really new to swift. It still gives me only the capital ones and i don't know how to change that it gives me the things behind de capital one as well.

Answer Source

(Swift 3)

We could let ourselves be inspired by the implementation of the split function in Sequence, and implement our own splitBefore method (split before separator, omitting empty subsequences), that keep the separators in the splitted sequence.

extension Sequence {
    func splitBefore(
        separator isSeparator: (Iterator.Element) throws -> Bool
    ) rethrows -> [AnySequence<Iterator.Element>] {
        var result: [AnySequence<Iterator.Element>] = []
        var subSequence: [Iterator.Element] = []

        var iterator = self.makeIterator()
        while let element = {
            if try isSeparator(element) {
                if !subSequence.isEmpty {
                subSequence = [element]
            else {
        return result

Used as follows

/* help property */
extension Character {
    var isUpperCase: Bool { return String(self) == String(self).uppercased() }

/* example usage */  
let teststring = "NaCuHHe"
let splitted = teststring
    .splitBefore(separator: { $0.isUpperCase })
print(splitted) // ["Na", "Cu", "H", "He"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download