Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to shift letters in a string x times by giving a slice of shifts in Swift

1 Answer

0 votes
/*
 string = "aaa"
 After shifting the first 1 letter by 1 = "baa"
 After shifting the first 2 letters by 2 = "dca"
 After shifting the first 3 letters by 3 = "gfd"
 result = "gfd"
*/

func shiftLetters(_ str: String, _ shifts: inout [Int]) -> String {
    let size = shifts.count
    var arr = Array(str)

    for i in stride(from: size - 1, through: 0, by: -1) {
        if i + 1 < size {
            shifts[i] += shifts[i + 1]
        }

        shifts[i] = shifts[i] % 26

        var asciiCode = Int(arr[i].asciiValue! - Character("a").asciiValue!)
        asciiCode += shifts[i]

        if asciiCode > 25 {
            asciiCode -= 26
        }

        arr[i] = Character(UnicodeScalar(Int(Character("a").asciiValue!) + asciiCode)!)
    }

    return String(arr)
}

var str = "aaa"
var shifts = [1, 2, 3]

str = shiftLetters(str, &shifts)

print(str)



/*
run:

gfd

*/

 



answered Dec 4, 2025 by avibootz

Related questions

...