重新排序 Swift 中的字符串字符

Reorder string characters in Swift

所以,假设我有一个字符串:"abc",我想更改每个字符的位置,以便我可以有 "cab" 和后来的 "bca"。我希望索引 0 的字符移动到 1,索引 1 的字符移动到 2,索引 2 的字符移动到 0。

我有什么 Swift 可以做到这一点?另外,假设我有数字而不是字母。有没有更简单的方法来处理整数?

Swift 2:

extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
  mutating func cycleAround() {
    insert(removeLast(&self), atIndex: startIndex)
  }
}

var ar = [1, 2, 3, 4]

ar.cycleAround() // [4, 1, 2, 3]

var letts = "abc".characters
letts.cycleAround()
String(letts) // "cab"

Swift 1:

func cycleAround<C : RangeReplaceableCollectionType where C.Index : BidirectionalIndexType>(inout col: C) {
  col.insert(removeLast(&col), atIndex: col.startIndex)
}

var word = "abc"

cycleAround(&word) // "cab"

Swift Algorithms package there is a rotate命令中

import Algorithms

let string = "abcde"
var stringArray = Array(string)
for _ in 0..<stringArray.count {
    stringArray.rotate(toStartAt: 1)
    print(String(stringArray))
}

结果:

bcdea
cdeab
deabc
eabcd
abcde