scala Scala反向字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7700399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:33:22  来源:igfitidea点击:

Scala reverse string

scala

提问by Dzhu

I'm a newbie to scala, I'm just writing a simple function to reverse a given string:

我是 Scala 的新手,我只是在编写一个简单的函数来反转给定的字符串:

def reverse(s: String) : String
  for(i <- s.length - 1 to 0) yield s(i)

the yield gives back a scala.collection.immutable.IndexedSeq[Char], and can not convert it to a String. (or is it something else?)

yield 返回一个 scala.collection.immutable.IndexedSeq[Char],并且不能将其转换为 String。(或者是别的什么?)

how do i write this function ?

我怎么写这个函数?

回答by om-nom-nom

Note that there is already defined function:

请注意,已经定义了函数:

scala> val x = "scala is awesome"
x: java.lang.String = scala is awesome

scala> x.reverse
res1: String = emosewa si alacs

But if you want to do that by yourself:

但如果你想自己做:

def reverse(s: String) : String =
(for(i <- s.length - 1 to 0 by -1) yield s(i)).mkString

or (sometimes it is better to use until, but probably not in that case)

或(有时最好使用until,但在这种情况下可能不是)

def reverse(s: String) : String =
(for(i <- s.length until 0 by -1) yield s(i-1)).mkString

Also, note that if you use reversed counting (from bigger one to less one value) you should specify negative step or you will get an empty set:

另外,请注意,如果您使用反向计数(从大一到小一值),您应该指定负步长,否则您将得到一个空集:

scala> for(i <- x.length until 0) yield i
res2: scala.collection.immutable.IndexedSeq[Int] = Vector()

scala> for(i <- x.length until 0 by -1) yield i
res3: scala.collection.immutable.IndexedSeq[Int] = Vector(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

回答by Luigi Plinge

Here's a short version

这是一个简短的版本

def reverse(s: String) = ("" /: s)((a, x) => x + a)


edit: or even shorter, we have the fantastically cryptic

编辑:或者更短,我们有非常神秘的

def reverse(s: String) = ("" /: s)(_.+:(_))

but I wouldn't really recommend this...

但我真的不会推荐这个......

回答by huynhjl

As indicated by om-nom-nom, pay attention to the by -1(otherwise you are not really iterating and your result will be empty). The other trick you can use is collection.breakOut.

正如 om-nom-nom 所指示的那样,注意by -1(否则你不是真正的迭代,你的结果将是空的)。您可以使用的另一个技巧是 collection.breakOut.

It can also be provided to the forcomprehension like this:

它也可以for像这样提供给理解:

def reverse(s: String): String  =
  (for(i <- s.length - 1 to 0 by -1) yield s(i))(collection.breakOut)

reverse("foo")
// String = oof

The benefit of using breakOutis that it will avoid creating a intermediate structure as in the mkStringsolution.

使用的好处breakOut是它将避免在mkString解决方案中创建中间结构。

note: breakOutis leveraging CanBuildFromand builders which are part of the foundation of the redesigned collection library introduced in scala 2.8.0

注意:breakOut正在利用CanBuildFrom和构建器,它们是 Scala 2.8.0 中引入的重新设计的集合库的基础的一部分

回答by Thomas Lockney

You could also write this using a recursive approach (throwing this one in just for fun)

您也可以使用递归方法编写它(只是为了好玩而将其放入)

def reverse(s: String): String = {
  if (s.isEmpty) ""
  else reverse(s.tail) + s.head
}

回答by Venkat Sudheer Reddy Aedama

All the above answers are correct and here's my take:

以上所有答案都是正确的,这是我的看法:

scala> val reverseString = (str: String) => str.foldLeft("")((accumulator, nextChar) => nextChar + accumulator)
reverseString: String => java.lang.String = <function1>

scala> reverseString.apply("qwerty")
res0: java.lang.String = ytrewq

回答by Igor Dorokhov

  def rev(s: String): String = {
    val str = s.toList
    def f(s: List[Char], acc: List[Char]): List[Char] = s match {
      case Nil => acc
      case x :: xs => f(xs, x :: acc)
    }
    f(str, Nil).mkString
  }