繁体   English   中英

从字符串打印偶数和奇数索引处的字符

[英]Print characters at even and odd indices from a String

使用scala,如何在给定字符串的偶数和奇数索引中打印字符串? 我知道使用var的命令式方法。 我正在寻找一种使用不变性、避免副作用(当然,直到需要打印结果)和简洁的方法。

另一种探索方式是使用zipWithIndex

def printer(evenOdd: Int) {
    val str = "1234"
    str.zipWithIndex.foreach { i =>
      i._2 % 2 match {
        case x if x == evenOdd => print(i._1)
        case _ =>
      }
    }
  }

在这种情况下,您可以使用打印机功能检查结果

scala> printer(1)
24
scala> printer(0)
13

.zipWithIndex接受一个List并返回元素的元组及其索引。 知道一个String是一个Char列表

看着str

scala> val str = "1234"
str: String = 1234

str.zipWithIndex
res: scala.collection.immutable.IndexedSeq[(Char, Int)] = Vector((1,0), (2,1), (3,2), (4,3))

最后,由于您只需要打印,使用foreach而不是map更理想,因为您不希望返回值

这是一个尾递归解决方案,一次性返回偶数和奇数字符(List[Char], List[Char])

def f(in: String): (List[Char], List[Char]) = {
  @tailrec def run(s: String, idx: Int, accEven: List[Char], accOdd: List[Char]): (List[Char], List[Char]) = {
    if (idx < 0) (accEven, accOdd)
    else if (idx % 2 == 0) run(s, idx - 1, s.charAt(idx) :: accEven, accOdd)
    else run(s, idx - 1, accEven, s.charAt(idx) :: accOdd)
  }
  run(in, in.length - 1, Nil, Nil)
}

可以这样打印

val (even, odd) = f("abcdefg")
println(even.mkString)

您可以使用sliding功能,这很简单:

scala> "abcdefgh".sliding(1,2).mkString("")
res16: String = aceg

scala> "abcdefgh".tail.sliding(1,2).mkString("")
res17: String = bdfh
val s = "abcd"
// ac
(0 until s.length by 2).map(i => s(i))
// bd
(1 until s.length by 2).map(i => s(i))

只是带有映射运算符的纯函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM