How do I shift array characters to the right in Java?

别说谁变了你拦得住时间么 提交于 2019-12-20 01:41:38

问题


This is what I have:

class encoded
{
    public static void main(String[] args)
    {
        String s1 = "hello";
        char[] ch = s1.toCharArray();
        for(int i=0;i<ch.length;i++)
        {
            char c = (char) (((i - 'a' + 1) % 26) + 'a');
            System.out.print(c);
        }
    }
}

So far I've converted the string to an array, and I've worked out how to shift, but now I'm stuck.

What I want is for the code to start at ch[0], read the character, shift it one to the right (h to i) and then do the same for each character in the array until it reaches the end.

Right now, my code outputs opqrs. I want it to output ifmmp. If I replace the int i = 0 in the for loop with int i = ch[0], it does start at i, but then it just inputs ijklmno...

I want it to read h, output as i, read e, output as f, and so on until it reaches the end of the array.


回答1:


You are using the loop index i instead of the ith character in your loop, which means the output of your code does not depend the input String (well, except for the length of the output, which is the same as the length of the input).

Change

char c = (char) (((i - 'a' + 1) % 26) + 'a');

to

char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');



回答2:


Replace i - 'a' + 1 with ch[i] - 'a' + 1

class encoded {

   public static void main(String[] args)
   {
     String s1 = "hello";
     char[] ch = s1.toCharArray();
     for(int i=0;i<ch.length;i++)
     { 
        char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');
        System.out.print(c);
     }
   }
}


来源:https://stackoverflow.com/questions/44105977/how-do-i-shift-array-characters-to-the-right-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!