scala反转字符串_Scala程序反转字符串

本文介绍在Scala中如何通过两种不同的方法实现字符串的反转。一种方法是使用循环逐个字符拼接,另一种方法是将字符串转化为列表,利用foldLeft函数进行反转,最后再转化为字符串。

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反转字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值