gpt4 book ai didi

string - 在 Swift 中重新排序字符串字符

转载 作者:行者123 更新时间:2023-11-30 10:13:50 25 4
gpt4 key购买 nike

所以,假设我有一个字符串:“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"

关于string - 在 Swift 中重新排序字符串字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31361709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com