簡體   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