2017-10-15 447 views
-1

我想編寫一個程序,該程序應該接受一個字符串,並按照字母順序將字符串中的每個字母替換爲下一個字母。那麼它應該將字母a,e,i,o,u轉換成大寫的字符串。例如,如果字符串是「你好嗎」,那麼它應該將其轉換爲「Ipx bsf zpv」。 我試過這個,但我被卡住了。另外,我認爲應該有一個更好的方法,而不是在我的程序中輸入那麼多。如何以字母順序替換字符串中的字母

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) 
    } 
    } 
    } 
+0

你嘗試谷歌你的問題? https://www.google.com.ua/search?q=replace+letter+next+letter –

+1

z呢?它應該旋轉到?這在大多數語言中是相似的,只是增加循環中字符的字節值。 – Piro

+0

[Letter→下一個字母和大寫元音]可能的重複(https://stackoverflow.com/questions/21296270/letter-%e2%86%92-next-letter-and-capitalize-vowels) –

回答

1

可以使用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 
1

使用collect並轉換字符串的每個字符。

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 
} 
相關問題