How to reverse only the alphabetic characters in a string, keeping other characters in place with Swift

1 Answer

0 votes
import Foundation

func reverseOnlyLetters(_ s: String) -> String {
    // Convert string to a character array for in-place modification
    var chars = Array(s)
    var left = 0
    var right = chars.count - 1
    
    while left < right {
        // Skip non-alphabetic characters from the left
        if !chars[left].isLetter {
            left += 1
        } 
        // Skip non-alphabetic characters from the right
        else if !chars[right].isLetter {
            right -= 1
        } 
        // If both are letters, swap them and move both pointers
        else {
            chars.swapAt(left, right)
            left += 1
            right -= 1
        }
    }
    
    return String(chars)
}

let s = "a1-bC2-dEf3-ghIj"
print(s)

let result = reverseOnlyLetters(s)
print(result) 



/*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz
edited Mar 7 by avibootz

Related questions

...