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.
To split a string on capital letters, call the split() method with the following regular expression - /(? =[A-Z])/ . The regular expression uses a positive lookahead assertion to split the string on each capital letter and returns an array of the substrings.
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
Using Regex -
func splitYourString(_ s: String) ->[String] {
let regex = try! NSRegularExpression(pattern: "([a-z]*)([A-Z])") //<-Use capturing, `([a-z]*)`->$1, `([A-Z])`->$2
return regex.stringByReplacingMatches(in: s, range: NSRange(0..<s.utf16.count),
withTemplate: "$1 $2").trimmingCharacters(in: .whitespacesAndNewlines) .components(separatedBy: " ")
}
print(splitYourString("NaCuHHe")) //["Na", "Cu", "H", "He"]
A bit late to the party, but here's a straightforward Swift 3 approach using whitespace-delimiting. Might not be as elegant as the functional or iterator approaches, but it doesn't involve making any custom extensions on existing classes.
let originalString = "NaCuHHe"
var newStringArray: [String] = []
for character in originalString.characters {
if String(character) == String(character).uppercased() {
newStringArray.append(" ")
}
newStringArray.append(String(character))
}
let newString = newStringArray.joined().trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
print(newString) // Returns ["Na", "Cu", "H", "He"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With