本文共 1452 字,大约阅读时间需要 4 分钟。
scala反转字符串
Logically, reversing is swapping the values from index 1 with index n, index 2 with index n-1, and so on.
从逻辑上讲,反向是将索引1中的值与索引n交换,将索引2中的值与索引n-1交换,依此类推。
So, if the string is "IncludeHelp", then the reverse will be "pleHedulcnI".
因此,如果字符串为“ IncludeHelp” ,则反向为“ pleHedulcnI” 。
Example:
例:
Input: String: "IncludeHelp" Output: Reversed string: "pleHedulcnI"
object myObject { def reverseString(newString: String): String = { var revString = "" val n = newString.length() for(i <- 0 to n-1){ revString = revString.concat(newString.charAt(n-i-1).toString) } return revString } def main(args: Array[String]) { var newString = "IncludeHelp" println("Reverse of '" + newString + "' is '" + reverseString(newString) + "'") }}
Output
输出量
Reverse of 'IncludeHelp' is 'pleHedulcnI'
Another method will be to convert the string into a list and then reversing the list and the converting in back to the string.
另一种方法是将字符串转换为列表,然后反转列表并将其转换回字符串。
Program:
程序:
object myObject { def main(args: Array[String]) { var newString = "IncludeHelp" var revString = newString.foldLeft(List[Char]()){(x,y)=>y::x}.mkString("") println("Reverse of '" + newString + "' is '" + revString + "'") }}
Output
输出量
Reverse of 'IncludeHelp' is 'pleHedulcnI'
翻译自:
scala反转字符串
转载地址:http://hhazd.baihongyu.com/