简体   繁体   English

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

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

Using scala, how to print string in even and odd indices of a given string?使用scala,如何在给定字符串的偶数和奇数索引中打印字符串? I am aware of the imperative approach using var .我知道使用var的命令式方法。 I am looking for an approach that uses immutability, avoids side-effects (of course, until need to print result) and concise.我正在寻找一种使用不变性、避免副作用(当然,直到需要打印结果)和简洁的方法。

Another way to explore is using zipWithIndex另一种探索方式是使用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 _ =>
      }
    }
  }

In this case you can check the results by using the printer function在这种情况下,您可以使用打印机功能检查结果

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

.zipWithIndex takes a List and returns tuples of the elements coupled with their index. .zipWithIndex接受一个List并返回元素的元组及其索引。 Knowing that a String is a list of Char知道一个String是一个Char列表

Looking at str看着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))

Lastly, as you only need to print, using foreach instead of map is more ideal as you aren't expecting values to be returned最后,由于您只需要打印,使用foreach而不是map更理想,因为您不希望返回值

Here is a tail-recursive solution returning even and odd chars (List[Char], List[Char]) in one go这是一个尾递归解决方案,一次性返回偶数和奇数字符(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)
}

which could be printed like so可以这样打印

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

You can use the sliding function, which is quite simple:您可以使用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))

just pure functions with map operator只是带有映射运算符的纯函数

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

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