Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick capital letters from a Swift string?

Tags:

string

ios

swift

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

like image 674
János Avatar asked Oct 23 '14 22:10

János


People also ask

How do you print a string in capital letters?

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.

How can we print all the capital letters of a given string in C?

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.


2 Answers

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()
like image 88
Gabriele Petronella Avatar answered Oct 26 '22 23:10

Gabriele Petronella


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"]
like image 24
Victor Sigler Avatar answered Oct 27 '22 01:10

Victor Sigler