How can I identify uppercase and lowercase characters in a string with swift?
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
In Swift 5, we can now check for character properties per Unicode standard.
For your question, chr.isUppercase
and chr.isLowercase
is the answer.
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
.
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.")
}
}