scala反转字符串
反转字符串 (Reversing a string)
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"
程序在Scala中反转字符串 (Program to reverse a string in Scala)
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'
翻译自: https://www.includehelp.com/scala/reverse-a-string.aspx
scala反转字符串
本文介绍在Scala中如何通过两种不同的方法实现字符串的反转。一种方法是使用循环逐个字符拼接,另一种方法是将字符串转化为列表,利用foldLeft函数进行反转,最后再转化为字符串。

2673

被折叠的 条评论
为什么被折叠?



