我有Strings
,我希望用uppercaseString
转换为lowercaseString
,only letters
。
我的琴弦;
let uppers = " Hello*im ; + Upper+String "
let lowers = " Hello*im ; + Lower+String "
print(uppers)
print(lowers)
大写输出看起来像这样
HELLOIMUPPERSTRING
谢谢!
答案 0 :(得分:5)
您可以使用Set
。
let uppers = " Hello*im ; + Upper+String "
let lowers = " Hello*im ; + Lower+String "
let allowChars : Set<Character> = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters)
let upperStr = String(uppers.characters.filter {allowChars.contains($0) }).uppercaseString
let lowerStr = String(lowers.characters.filter {allowChars.contains($0) }).lowercaseString
print(upperStr)
print(lowerStr)
修改:要允许空格,还要在Set
字符内添加其他字符的空格
let allowChars : Set<Character> = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters)
答案 1 :(得分:1)
首先从非字母数字字符中删除字符串,然后转换为小写或大写。
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
let strippedReplacement = " ".join(myString.componentsSeparatedByCharactersInSet(charactersToRemove))
let resultUppercase = strippedReplacement.uppercaseString
let resultLowercase = strippedReplacement.lowercaseString