2017-02-19 46 views
1

是否有任何特定的API來獲取字符的下一個字母表?獲取字符的下一個字母表

例子:

如果"Somestring".characters.first導致"S",那麼應該 返回"T"

如果有沒有我想我有過字母表的集合迭代和順序返回下一個字符。或者還有其他更好的解決方案嗎?

+0

也許你應該得到的字符的ASCII值的下一個迭代 –

回答

2

如果你覺得拉丁大寫字母「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 
    } 
} 

如果有, 和nil它返回的下一個大寫拉丁字母除此以外。它的工作原理是因爲拉丁文大寫字母 具有連續的Unicode標量值。 (請注意,UnicodeScalar(uniCode.value + 1)!不能在該 範圍內失敗。)guard語句處理多字符 字符串和擴展字形羣集(例如標誌「」)。

您可以使用

case "A" ..< "Z", "a" ..< "z": 

如果小寫字母應,以及覆蓋。

例子:

nextLetter("B") // C 
nextLetter("Z") // nil 
nextLetter("€") // nil 
+0

還請注意,我們可以捕捉_「檢查是否字符串是從只有一個Unicode標建」 _與邏輯通過'String'初始化器('String' initializer](https://developer.apple.com/reference/swift/unicodescalar/2430716-init)對failable ['UnicodeScalar')進行單個調用,我們可以在其上應用一個'flatMap',其中包含一個三元評估(對於模式匹配),有條件地返回下一個字母「String」。例如,真的沒有什麼好的理由可以將上面的正文縮小到:'返回UnicodeScalar(letter).flatMap {「A」.. <「Z」〜= $ 0?字符串(UnicodeScalar($ 0.value + 1)!):nil}' – dfri

+0

...'UnicodeScalar'初始值設定項[看似完全一樣的工作](https://github.com/apple/swift/blob/master/ stdlib/public/core/UnicodeScalar.swift#L285)對於我們來說,就像上面明確表達的一樣(我只是想知道爲什麼他們會使用'description'作爲內部名稱,因爲這通常是一個紅色的標誌,以供我明確使用)。 – dfri

+1

@dfri:非常好的建議! (但我會保持開關/案例的清晰:) –

2
func nextChar(str:String) { 
    if let firstChar = str.unicodeScalars.first { 
     let nextUnicode = firstChar.value + 1 
     if let var4 = UnicodeScalar(nextUnicode) { 
      var nextString = "" 
      nextString.append(Character(UnicodeScalar(var4))) 
      print(nextString) 
     } 
    } 
} 
nextChar(str: "A") // B 
nextChar(str: "ζ") // η 
nextChar(str: "z") // { 
+0

我不能接受這兩個答案,但因爲我沒有指定我只接受問題中的拉丁字母,因此我贊成你的回答作爲回報。乾杯。 – John

相關問題