Scala函数获取下一个字母表的字母

时间:2011-04-21 21:43:34

标签: scala string

寻找要做的事情:

Given input: "s"
Expected output: "t"

3 个答案:

答案 0 :(得分:5)

scala> def f(s: String) = (s.head + 1).toChar.toString
f: (s: String)java.lang.String

scala> f("s")
res10: java.lang.String = t

答案 1 :(得分:4)

def nextLetter(x:String) = (x(0) + 1).toChar.toString

答案 2 :(得分:2)

这些方法仅为字母返回有意义的结果:

def nextLetter(letter: Char): Option[Char] = {
  val validChars = ('a' to 'y') ++ ('A' to 'Y')
  if (validChars contains letter) Some((letter + 1).toChar) else None
}

def nextLetter(letter: String): Option[String] = {
  if (letter.length != 1) None
  else nextLetter(letter(0)).map(_.toString)
}

println(nextLetter('a'))
println(nextLetter('b'))
println(nextLetter('z'))
println(nextLetter('1'))
println(nextLetter('A'))
println(nextLetter("A"))
println(nextLetter("AB"))