Search code examples
stringswiftindexingintegercharacter

Reorder string characters in Swift


So, let's say I have a String that is: "abc" and I want to change each character position so that I can have "cab" and later "bca". I want the character at index 0 to move to 1, the one on index 1 to move to 2 and the one in index 2 to 0.

What do I have in Swift to do this? Also, let's say instead of letters I had numbers. Is there any easier way to do it with integers?


Solution

  • 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"