简体   繁体   中英

How to swap two characters in String Swift4?

in Swift4, the String is Collections. You will no longer use characters property on a string.

func swapCharacters(input:String,index1:Int,index2:Int)-> String { // logic to swap }

let input = "ABCDEFGH"

If I call the function with (input,3,8) then the output should be

Output: ABC H EFG D

Note: In Swift4, Strings are collections.

Fairly straightforward since String is a collection:

func swapCharacters(input: String, index1: Int, index2: Int) -> String {
    var characters = Array(input)
    characters.swapAt(index1, index2)

    return String(characters)
}

let input = "ABCDEFGH"
print(swapCharacters(input: input, index1: 3, index2: 7)) //ABCHEFGD

or, to provide a direct array-like operation:

extension String {
    mutating func swapAt(_ index1: Int, _ index2: Int) {
        var characters = Array(self)
        characters.swapAt(index1, index2)
        self = String(characters)
    }
}

var input = "ABCDEFGH"
input.swapAt(3, 7)
print(input) //ABCHEFGD

If you are looking for String manipulation without converting it to array. I won't say it's great solution, but does its job.

func swapCharacters(input: String, index1: Int, index2: Int) -> String {
var result = input
let index1Start = input.index(input.startIndex, offsetBy: index1)
let index1End = input.index(after: index1Start)

let index2Start = input.index(input.startIndex, offsetBy: index2)
let index2End = input.index(after: index2Start)

let temp = input[index2Start..<index2End]
result.replaceSubrange(index2Start..<index2End,
                       with: input[index1Start..<index1End])
result.replaceSubrange(index1Start..<index1End, with: temp)

return result

}

print(swapCharacters(input: "ABCDEFGH", index1: 3, index2: 7))

prints: ABC H EFG D

Your question doesn't make sense. Strings in Swift are not indexed by Int. You need to first figure out for yourself what a Character really is (an Extended Grapheme Cluster). Then you need to figure out why Int cannot be used as the index for Strings. And then you can come up with a real problem. Read up here:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM