【问题标题】:Reorder string characters in Swift在 Swift 中重新排序字符串字符
【发布时间】:2015-09-30 10:32:04
【问题描述】:

所以,假设我有一个字符串:“abc”,我想更改每个字符的位置,这样我就可以有“cab”,然后是“bca”。我希望索引 0 处的字符移动到 1,索引 1 上的字符移动到 2,索引 2 中的字符移动到 0。

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

【问题讨论】:

    标签: string swift indexing integer character


    【解决方案1】:

    斯威夫特 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"
    

    斯威夫特 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"
    

    【讨论】:

    • OP 希望最后一个字符移到开头,而不是第一个字符移到末尾。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 2018-08-14
    相关资源
    最近更新 更多