How to swap two characters in String Swift4?
Asked Answered
D

3

7

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 : ABCHEFGD

Note: In Swift4, Strings are collections.

Dunaville answered 26/12, 2017 at 17:42 Comment(4)
what have you tried? Why swap B and C, because you always want to switch B and C or because they are at index 1 and 2 or because they are in the middle or because they are next to each other?Dimple
@kumar Reddy on what algo are you selecting B & C for swap? What if string goes ABCDFGHRFYUJITR?Eristic
updated the question.Dunaville
Possible duplicate of How to replace nth character of a string with anotherEvalynevan
V
6

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
Villeinage answered 26/12, 2017 at 18:12 Comment(5)
Whats is the time complexity of your solution? I see you are creating new String on each mutation. Is it O(n)?Mockheroic
@Mockheroic It's obviously O(n) depending on the length of the String. If you need lots of similar operations, you should use arrays of characters instead of a String because the conversion from String to [Character] is the slow thing here.Villeinage
If this is the case, do you think replacing Sequence at the given range would be a better option? At least it wouldn’t be O(n).Mockheroic
@Mockheroic I don't think it would help much. String characters are not the same length - String can store them in different ways, and that means that replacing a character can actually mean changing the whole sequence of bytes. With short strings the difference will be probably negligible anyway.Villeinage
But it’s worth mentioning that if you are dealing with utf8 sequence then replacing a range might be of benefit.Mockheroic
J
0

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: ABCHEFGD

Juetta answered 22/9, 2022 at 20:25 Comment(0)
P
-5

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

Permeability answered 26/12, 2017 at 18:10 Comment(2)
I am solving data structure problems in Swift while doing the permutations for a string i need to swap the elements. So how should I do that without accessing the index?Dunaville
"Int cannot be used as the index for Strings"?? For a given Swift string value are there not a countable and ordered set of indexes? That Swift choose not to use integers is just that, a choice - maybe a good one, maybe not, but there is no cannot here surely?Bruges

© 2022 - 2024 — McMap. All rights reserved.