我是scala语言的新手,我需要的是我想循环旋转一串字符,例如字符串=" love",当我们执行循环旋转时,此结果应该像这个字符串" elov&#34 ;.这是我写的代码
import scala.util.control._
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List
object StringAlgorithm {
def swap(s : String, idx1 : Int, idx2 : Int){
val cs = s.toCharArray
val swp = cs(idx1)
cs(idx1) = cs(idx2)
cs(idx2) = swp
println(cs)
}
def main(args: Array[String}){
var str2 ="ovel"
var str2len = str2.length()
val LastIndex = str2len -1
println(LastIndex)
//val cs = Array[Char](4)
//println(cs)
var i : Int = 0
for(i <- 0 to LastIndex){
swap(str2, i, LastIndex)
}
println(str2)
}
}
object test {
def main(args: Array[String]) {
var str = "Hello"
println(str)
var str1 = str.toList
println(str1)
val str1en = (str1.length) - 1
println(str1en)
for ( i <- 0 to str1en){
var temp = str1(i)
var temp1 = str1(str1en)
str1.updated(i, temp1)
str1.updated(str1en, temp)
}
println(str1)
}
}
答案 0 :(得分:1)
这是一个相当直接的Scala-ish解决方案
val str = "Hello"
for {i <- 1 until str.length
(a,b) = str.splitAt(i)}
yield b + a
// Vector(elloH, lloHe, loHel, oHell)
使用迭代器的版本(稍微少于Scala-ish?)
Iterator.iterate(str){s=>s.last + s.init}.take(str.length).toList
更直接地使用List伴侣对象
中的方法List.iterate(str, str.length){s=>s.last + s.init}
答案 1 :(得分:1)
这是我的想法:
def cycleOnce(word: String): String = word.last + word.init
def cycled(word: String) = (1 until word.size)
.foldLeft(List(word))((list, _) => cycleOnce(list.head) :: list).reverse
使用:
scala> cycled("love")
res4: List[String] = List(love, elov, velo, ovel)