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

前端 未结 2 479
轮回少年
轮回少年 2021-01-20 02:14

This is what I have:

class encoded
{
    public static void main(String[] args)
    {
        String s1 = \"hello\";
        char[] ch = s1.toCharArray();
           


        
相关标签:
2条回答
  • 2021-01-20 02:30

    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);
         }
       }
    }
    
    0 讨论(0)
  • 2021-01-20 02:43

    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');
    
    0 讨论(0)
提交回复
热议问题