Scala:slice()没有按预期执行

时间:2016-07-09 01:01:18

标签: scala output slice

我正在写一小段代码,它将遍历一个1000位的数字,每一步取13个数字。对于例如在第一次迭代中,它应该取0-13位的数字,在下一次迭代中它应该取1-14位的数字,依此类推。这是我的代码,但是当我遍历大数字时,我的切片越来越小。我想每次从原始字符串中切出13位数字。我做错了什么?

val largeNumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
var current13Digits = ""

for (iterator <- 0 to (largeNumber.length-13))
  {
            println("CURRENT VALUE OF ITERATOR IS " + iterator)
            current13Digits = largeNumber.slice(iterator,13)
            println("CURRENT 13 DIGITS ARE " + current13Digits)
  }

输出如下,每个切片后都会丢失数字。我做错了什么?

CURRENT VALUE OF ITERATOR IS 0
CURRENT 13 DIGITS ARE 7316717653133
CURRENT VALUE OF ITERATOR IS 1
CURRENT 13 DIGITS ARE 316717653133
CURRENT VALUE OF ITERATOR IS 2
CURRENT 13 DIGITS ARE 16717653133
CURRENT VALUE OF ITERATOR IS 3
CURRENT 13 DIGITS ARE 6717653133
CURRENT VALUE OF ITERATOR IS 4
CURRENT 13 DIGITS ARE 717653133
CURRENT VALUE OF ITERATOR IS 5
CURRENT 13 DIGITS ARE 17653133
CURRENT VALUE OF ITERATOR IS 6
CURRENT 13 DIGITS ARE 7653133
CURRENT VALUE OF ITERATOR IS 7
CURRENT 13 DIGITS ARE 653133
CURRENT VALUE OF ITERATOR IS 8
CURRENT 13 DIGITS ARE 53133
CURRENT VALUE OF ITERATOR IS 9
CURRENT 13 DIGITS ARE 3133
CURRENT VALUE OF ITERATOR IS 10
CURRENT 13 DIGITS ARE 133
CURRENT VALUE OF ITERATOR IS 11
CURRENT 13 DIGITS ARE 33
CURRENT VALUE OF ITERATOR IS 12
CURRENT 13 DIGITS ARE 3
CURRENT VALUE OF ITERATOR IS 13
CURRENT 13 DIGITS ARE 
CURRENT VALUE OF ITERATOR IS 14
CURRENT 13 DIGITS ARE 
CURRENT VALUE OF ITERATOR IS 15
CURRENT 13 DIGITS ARE .....

1 个答案:

答案 0 :(得分:-2)

谢谢,滑动效果很好。

val current13Digits = largeNumber.sliding(13)
while(current13Digits.hasNext)
  {
    current13DigitsAsString = current13Digits.next()
    println("CURRENT 13 DIGITS ARE " + current13DigitsAsString
    ...
  }