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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,037 questions

40,897 answers

573 users

How to shift letters in a string x time by giving an array of shifts in Java

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


public class Program {
    static String shifLetters(String str, int[] shifts) {
        int size = shifts.length;
        
        char[] arr = str.toCharArray();
        
        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.charAt(i) - 'a';
            asciicode = asciicode + shifts[i];
            if (asciicode > 25) {
                asciicode = asciicode - 26;
            }               
            arr[i] = (char)('a' + asciicode);
        }
        
        return new String(arr);
    }

    public static void main(String[] args) {
        String str = "aaa";
	    
	    int[] shifts = {1, 2, 3};

	    str = shifLetters(str, shifts);

	    System.out.print(str);
    }
}



/*
run:
 
gfd
 
*/

 





answered Feb 27 by avibootz
edited Feb 27 by avibootz
...