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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to shift letters in a string x times by given a vector of shifts in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

/*

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 3 = "gfd"
result = "gfd"

*/

std::string shifLetters(std::string str, std::vector<int>& shifts) {
    int size = str.size();   
    
    for (int i = size - 1 ; i >= 0; i--) {
        if (i + 1 < size) {
            shifts[i] += shifts[i + 1];
        }
        shifts[i] = shifts[i] % 26;
        int asciicode = str[i] - 'a';
        asciicode = asciicode + shifts[i];
        if (asciicode > 25) { 
            asciicode = asciicode - 26;
        }
        str[i] = (char)('a' + asciicode); 
    }
       
    return str;
}
    
int main() {
    std::string str = "aaa";
    std::vector<int> shifts = {1, 2, 3};
    
    str = shifLetters(str, shifts);
    
    std::cout << str;
}

 
 
 
/*
run:
 
gfd
 
*/

 



answered Feb 27, 2024 by avibootz
edited Feb 27, 2024 by avibootz

Related questions

...