Reputation: 3092
I would like to generate a list of words form a given string where each listed word contains at least an upper case letter.
Having a string like this one:
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?
Upvotes: 4
Views: 315
Reputation: 15784
You can use built in function of String in Swift that get all words of a string. It's better than just separate by a space (" ") cause you can have some words with a point (like 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)
}
}
Upvotes: 3
Reputation: 9691
You can probably do something like this. I haven't tested it, just wrote it real quick.
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)
}
}
Upvotes: 0
Reputation: 2447
var list = str.componentsSeparatedByString(" ").filter{ $0.lowercaseString != $0 }
Upvotes: 12