I need capital letters from a string. With NSString
it was sth like:
for (var i = 0; i<str.length; i++) {
let c = str.characterAtIndex(i)
if c >= 'A' && c < 'Z' {
//..
}
}
In Swift it starts like:
for (var i = 0; i<countElements(str); i++) {
//..
}
But I do not know i.e. how to pick i-th character, I am checking this
We can print all the uppercase letters by iterating the characters of a string in a loop and check individual characters are uppercase letters or not using isUpperCase() method and it is a static method of a Character class.
printf(“%c”,toupper(ch)); This printf() statement is printing the upper case value of the variable ch. This will be executed only when the above if statement becomes true.
Here's a slightly more idiomatic version in swift
func capitalLetters(s: String) -> [Character] {
return filter(s) { ("A"..."Z").contains($0) }
}
capitalLetters("fOo BAr") // ["O", "B", "A"]
or even:
func capitalLetters(s: String) -> [Character] {
func isCapital(c: Character) -> Bool {
return ("A"..."Z").contains(c)
}
return filter(s, isCapital)
}
capitalLetters("fOo BAr")
or also, you could make the syntax nicer by providing an extension
extension String {
func capitalLetters() -> [Character] {
func isCapital(c: Character) -> Bool {
return ("A"..."Z").contains(c)
}
return filter(self, isCapital)
}
}
"fOo BAr".capitalLetters()
For example this work fine in Swift :
var st = "Hello World"
for ch in st {
if ch >= "A" && ch <= "Z"{
println(ch)
}
}
And print
H
W
Or you could this instead :
var range = "A"..."Z"
for ch in st {
if range.contains(String(ch)) {
println(ch)
}
}
Or the solution of @Gabrielle updated to Swift 2.0:
func capitalLetters(s: String) -> [Character] {
return s.characters.filter { ("A"..."Z").contains($0) }
}
capitalLetters("fOo BAr") // ["O", "B", "A"]
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