arraysswiftstringsplit

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.


Solution

  • (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 = iterator.next() {
                if try isSeparator(element) {
                    if !subSequence.isEmpty {
                        result.append(AnySequence(subSequence))
                    }
                    subSequence = [element]
                }
                else {
                    subSequence.append(element)
                }
            }
            result.append(AnySequence(subSequence))
            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
        .characters
        .splitBefore(separator: { $0.isUpperCase })
        .map{String($0)}
    print(splitted) // ["Na", "Cu", "H", "He"]