Reputation: 446
I don't know how to seperate words by looking its all capital letters or not and assign them into an array.
var myString2 : String = "Cities of Illinois are CHICAGO PEORIA ROCKFORD"
Desired output
Thanks in advance
Upvotes: 0
Views: 65
Reputation: 5679
You can use the following line to get the desired array:
let array = myString2.components(separatedBy: " ").filter({ $0.compare($0.uppercased()) == .orderedSame })
Steps:
let arr = myString2.components(separatedBy: " ")
let filteredArray = arr.filter({ $0.compare($0.uppercased()) == .orderedSame })
Upvotes: 0
Reputation: 47896
Maybe you can use regular expression to achieve what you want.
var myString2 : String = "Cities of Illinois are CHICAGO PEORIA ROCKFORD"
let pattern = "\\b[A-Z]+\\b"
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: myString2, range: NSRange(0..<myString2.utf16.count))
let myArray = matches.map {String(myString2[Range($0.range, in: myString2)!])}
print(myArray) //->["CHICAGO", "PEORIA", "ROCKFORD"]
Upvotes: 1