[英]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.