我正在尝试创建一个将字符串存储在名为input
的变量中的程序。
使用此input
变量,然后我尝试将其转换为数组,然后使用for循环测试数组中的每个字符是否为lowerCase。我怎样才能做到这一点?
这是我走了多远:
var input = "The quick BroWn fOX jumpS Over tHe lazY DOg"
var inputArray = Array(input)
for character in inputArray {
/*
if character is lower case {
make it uppercase
} else {
make it lowercase
}
*/
}
答案 0 :(得分:4)
var input = "The quick BroWn fOX jumpS Over tHe lazY DOg"
var inputArray = Array(input)
for character in inputArray {
var strLower = "[a-z]";
var strChar = NSString(format: "%c",character )
let strTest = NSPredicate(format:"SELF MATCHES %@", strLower );
if strTest .evaluateWithObject(strChar)
{
// lower character
}
else
{
// upper character
}
}
答案 1 :(得分:4)
Swift 3
static func isLowercase(string: String) -> Bool {
let set = CharacterSet.lowercaseLetters
if let scala = UnicodeScalar(string) {
return set.contains(scala)
} else {
return false
}
}
答案 2 :(得分:1)
var input = "The quick BroWn fOX jumpS Over tHe lazY DOg"
let uppers = CharacterSet.uppercaseLetters
let lowers = CharacterSet.lowercaseLetters
input.unicodeScalars.forEach {
if uppers.contains($0) {
print("upper: \($0)")
} else if lowers.contains($0) {
print("lower: \($0)")
}
}
答案 3 :(得分:0)
你应该使用regexp:grep [A-Z]与grep [a-z]。
答案 4 :(得分:0)
这是一个写在Swift 4上的答案,输入字符串是一个或多个字母:
extension String {
static func isLowercase(string: String) -> Bool {
let set = CharacterSet.lowercaseLetters
for character in string {
if let scala = UnicodeScalar(String(character)) {
if !set.contains(scala) {
return false
}
}
}
return true
}
static func isUppercase(string: String) -> Bool {
let set = CharacterSet.uppercaseLetters
for character in string {
if let scala = UnicodeScalar(String(character)) {
if !set.contains(scala) {
return false
}
}
}
return true
}
}
答案 5 :(得分:0)
如果必须的话,我可能会编写如下代码:
extension Character {
func isMember(of set: CharacterSet) -> Bool {
guard let scalar = UnicodeScalar(String(self)) else { return false }
return set.contains(scalar)
}
var isUppercase: Bool {
return isMember(of: .uppercaseLetters)
}
// var isLowercase, isWhitespace, etc.
}
let result = "The quick BroWn fOX jumpS Over tHe lazY DOg"
.map { $0.isUppercase ? String($0).lowercased() : String($0).uppercased() }
.joined()
print(result)
// "tHE QUICK bROwN Fox JUMPs oVER ThE LAZy doG"
答案 6 :(得分:-3)
你可以检查每个字符的ascii值,因为大写和小写是不同的值,因为上面是65-90而下面是97-122