是否有任何特定的 API 来获取字符的下一个字母表?
例子:
如果
"Somestring".characters.first结果为"S",则应返回"T"
如果没有,我想我必须遍历一组字母表并按顺序返回下一个字符。或者有其他更好的解决方案吗?
如果您想到拉丁大写字母“A”...“Z”,那么以下应该有效:
func nextLetter(_ letter: String) -> String? {
// Check if string is build from exactly one Unicode scalar:
guard let uniCode = UnicodeScalar(letter) else {
return nil
}
switch uniCode {
case "A" ..< "Z":
return String(UnicodeScalar(uniCode.value + 1)!)
default:
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
如果有,则返回下一个拉丁大写字母,nil否则返回。它起作用是因为拉丁大写字母具有连续的 Unicode 标量值。(请注意,UnicodeScalar(uniCode.value + 1)!在该范围内不能失败。)该guard语句处理多字符串和扩展字素簇(例如标志“”)。
您可以使用
case "A" ..< "Z", "a" ..< "z":
Run Code Online (Sandbox Code Playgroud)
如果小写字母也应该被覆盖。
例子:
nextLetter("B") // C
nextLetter("Z") // nil
nextLetter("€") // nil
Run Code Online (Sandbox Code Playgroud)
func nextChar(str:String) {\n if let firstChar = str.unicodeScalars.first {\n let nextUnicode = firstChar.value + 1\n if let var4 = UnicodeScalar(nextUnicode) {\n var nextString = ""\n nextString.append(Character(UnicodeScalar(var4)))\n print(nextString)\n }\n }\n}\nnextChar(str: "A") // B\nnextChar(str: "\xce\xb6") // \xce\xb7\nnextChar(str: "z") // {\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3310 次 |
| 最近记录: |