我想编写一个程序,该程序应该接受一个字符串,并按字母顺序将字符串中的每个字母替换为下一个字母。然后它应该转换字母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 :(得分: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
}
答案 1 :(得分: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