Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I identify uppercase and lowercase characters in a string with swift?

Tags:

swift

This is what I have so far (for testing purpose):

let string = "The quick BroWn fOX jumpS Over tHe lazY DOg"

for chr in string {
    if isupper(String(chr)) {
        print(String(chr).lowercaseString)
        continue
    }
    print(chr)
}

how can I test for uppercase and lowercase characters?

I know I can call C functions from swift, but this does not seems to be correct for me. How can I do this with swift only?

like image 228
yeyo Avatar asked Jun 17 '14 16:06

yeyo


People also ask

Is uppercase A Swift?

To convert a String to Uppercase in Swift, use String. uppercased() function. Call uppercased() function on the String.

How do you check if all letters in a string are lowercase?

The islower() method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False.

How do you know if a string is uppercase or lowercase?

Traverse the string character by character from start to end. If the ASCII value lies in the range of [65, 90], then it is an uppercase letter. If the ASCII value lies in the range of [97, 122], then it is a lowercase letter. If the ASCII value lies in the range of [48, 57], then it is a number.

How to access the contents of a string in Swift?

The contents of a String can be accessed in various ways, including as a collection of Character values. Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code.

What are string and character types in Swift?

Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code.

What are substrings in Swift and how to use them?

Substrings in Swift have most of the same methods as strings, which means you can work with substrings the same way you work with strings. However, unlike strings, you use substrings for only a short amount of time while performing actions on a string. When you’re ready to store the result for a longer time,...


4 Answers

I am not sure what you mean by trying to avoid C functions. I hope this does not include avoiding the frameworks and foundational libraries that OS X and iOS offer you when developing an app, like, for instance, the NSCharacterSet class which provides exactly what you need in a Unicode compatible implementation.

To expand on Matt's answer, bringing it a little closer to your question's requirements:

import UIKit

let testString = "Åke röstet un café in Владивосток!"
let lowerCase = NSCharacterSet.lowercaseLetterCharacterSet()
let upperCase = NSCharacterSet.uppercaseLetterCharacterSet()

for currentCharacter in testString.utf16 {
  if lowerCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is lowercase.")
  } else if upperCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is UPPERCASE.")
  } else {
    println("Character code \(currentCharacter) is neither upper- nor lowercase.")
  }
}

Swift 3

let testString = "Åke röstet un café in Владивосток!"
let lowerCase = CharacterSet.lowercaseLetters
let upperCase = CharacterSet.uppercaseLetters

for currentCharacter in testString.unicodeScalars {
    if lowerCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is lowercase.")
    } else if upperCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is UPPERCASE.")
    } else {
        print("Character code \(currentCharacter) is neither upper- nor lowercase.")
    }
}
like image 64
guidos Avatar answered Oct 26 '22 07:10

guidos


You could always see if the lowercase representation is different from the current value;

let string = "The quick BroWn fOX jumpS Over tHe lazY DOg"
var output = ""

for chr in string {
    var str = String(chr)
    if str.lowercaseString != str {
        output += str
    }
}
print(output)

>>> TBWOXSOHYDO
like image 22
Joachim Isaksson Avatar answered Oct 26 '22 07:10

Joachim Isaksson


In Swift 5, we can now check for character properties per Unicode standard.

For your question, chr.isUppercase and chr.isLowercase is the answer.

like image 41
Thanh Pham Avatar answered Oct 26 '22 09:10

Thanh Pham


By extending String and Character I think I've arrived at a fairly flexible solution that is fully(?) Unicode aware. The syntax below is for Swift 3.0. Though there is nothing here that should not be possible in Swift 2.x.

extension String {
    func isUppercased(at: Index) -> Bool {
        let range = at..<self.index(after: at)
        return self.rangeOfCharacter(from: .uppercaseLetters, options: [], range: range) != nil
    }
}

extension Character {
    var isUppercase: Bool {
      let str = String(self)
      return str.isUppercased(at: str.startIndex)
    }
}

let str = "AaÀàΓγ!2😂🇺🇸"
let uppercase = str.characters.filter({ $0.isUppercase }) // ["A", "À", "Γ"]
for char in str.characters {
    "\(char): \(char.isUppercase)"
}

// A: true
// a: false
// À: true
// à: false
// Γ: true
// γ: false
// !: false
// 2: false
// 😂: false
// 🇺🇸: false

The TODO for these extensions is to refactor isUppercase on Character to not convert to String.

like image 28
Ryan Avatar answered Oct 26 '22 08:10

Ryan