How to create a list of words containing uppercase letters in swift?

I would like to generate a list of words from a given line, where each specified word contains at least an uppercase letter.

Having a line like this:

let str: String = "Apple watchOS 3 USA release date and feature rumours."

I would like to get an array like this:

var list: [String] = ["Apple", "watchOS", "USA"]

What is the best way to do this?

+4
source share
3 answers
var list = str.componentsSeparatedByString(" ").filter{ $0.lowercaseString != $0 }
+11
source

You can use Swift's built-in String function, which gets all the words in a string. This is better than just separating with a space (""), because you can have multiple words with a period (for example, the example below)

let str = "Apple watchOS 3 USA release date and feature Rumours."
var list = [String]()
str.enumerateSubstringsInRange(str.startIndex..<str.endIndex, options:.ByWords) { 
    (substring, substringRange, enclosingRange, value) in
    //add to your array if lowercase != string original
    if let _subString = substring where _subString.lowercaseString != _subString {
        list.append(_subString)
    }
}
+3
source

, - . , .

let str = "Apple watchOS 3 USA release date and feature rumours."
let strArr = str.componentsSeparatedByString(" ")
var upperWords: Array<String> = []
for word in strArr {
    if word != word.lowercaseString {
        upperWords.append(word)
    }
}
0

All Articles