Scala 如何按字母顺序替换字符串中的字母

Scala 如何按字母顺序替换字符串中的字母,scala,Scala,我想写一个程序,它应该用一个字符串替换字符串中的每个字母,然后按字母顺序替换下一个字母。然后它应该将字母a、e、i、o、u(如果它们存在于字符串中)转换为大写。例如,如果字符串为“你好”,则应将其转换为“Ipx bsf zpv”。 我已经试过了,但是我被卡住了。此外,我认为应该有更好的方法,而不是在我的程序中输入那么多if-else object Foo { def main(args: Array[String]) { val a: String = "How are you"

我想写一个程序,它应该用一个字符串替换字符串中的每个字母,然后按字母顺序替换下一个字母。然后它应该将字母a、e、i、o、u(如果它们存在于字符串中)转换为大写。例如,如果字符串为“你好”,则应将其转换为“Ipx bsf zpv”。 我已经试过了,但是我被卡住了。此外,我认为应该有更好的方法,而不是在我的程序中输入那么多if-else

object Foo {
  def main(args: Array[String]) {
    val a: String = "How are you"
    val d:String = ""
    var l = a.length
    var i:Int = 0
    while(l != 0){
      while(i != a.length) {
        if (a(i) == 'a')
        d charAt(_) = 'b'
        else if (a(i) == 'b')
        d charAt(_) = 'c'
        else if (a(i) == 'c')
        d charAt(_) = 'd'
        else if (a(i) == 'd')
        d charAt(_) = 'e'
        else if (a(i) == 'e')
        d charAt(_) = 'f'
        else if (a(i) == 'f')
        d charAt(_) = 'g'
        else if (a(i) == 'g')
        d charAt(_) = 'h'
        else if (a(i) == 'h')
        d charAt(_) = '_'
        else if (a(i) == '_')
        d charAt(_) = 'j'
        else if (a(i) == 'j')
        d charAt(_) = 'k'
        else if (a(i) == 'k')
        d charAt(_) = 'l'
        else if (a(i) == 'l')
          d charAt(_) = 'm'
        else if (a(i) == 'm')
          d charAt(_) = 'n'
        else if (a(i) == 'n')
          d charAt(_) = 'o'
        else if (a(i) == 'o')
          d charAt(_) = 'p'
        else if (a(i) == 'p')
          d charAt(_) = 'q'
        else if (a(i) == 'q')
          d charAt(_) = 'r'
        else if (a(i) == 'r')
          d charAt(_) = 's'
        else if (a(i) == 's')
          d charAt(_) = 't'
        else if (a(i) == 't')
          d charAt(_) = 'u'
        else if (a(i) == 'u')
          d charAt(_) = 'v'
        else if (a(i) == 'v')
          d charAt(_) = 'w'
        else if (a(i) == 'w')
          d charAt(_) = 'x'
        else if (a(i) == 'x')
          d charAt(_) = 'y'
        else if (a(i) == 'y')
          d charAt (_) = 'z'

      }
        i = i + 1
        l = l - 1
      var acc:String = acc + d(0)
      println(acc)
    }
  }
  }

使用
收集
并转换字符串的每个字符

val vowels = Set('a', 'e', 'i', 'o', 'u')

str.collect {
 case x if x == ' ' => ' '
 case x if vowels(x) => x.toUpper
 case x => (x.toByte + 1).toChar
}

您可以使用
map
功能,如下所示

val str = "how are you"

val transformedStr = str.map(x => x match {
  case ' ' => ' '
  case y => {
    val convertedChar = (y.toByte+1).toChar
    if(Array('a', 'e', 'i', 'o', 'u').contains(convertedChar)) convertedChar.toUpper
    else convertedChar
  }
})

println(transformedStr)
最终转换的字符串应为

Ipx bsf zpv

你试过用谷歌搜索你的问题吗?z呢。它应该旋转到一个合适的位置吗?这在大多数语言中是类似的,只是增加循环中字符的字节值