如何在Java中将数组字符向右移? [英] How do I shift array characters to the right in Java?

查看:254
本文介绍了如何在Java中将数组字符向右移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

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.

我想要的代码是从ch[0]开始,读取字符,将其向右移一个(hi),然后对数组中的每个字符执行相同的操作,直到到达结束.

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.

现在,我的代码输出opqrs.我希望它输出ifmmp.如果我将for循环中的int i = 0替换为int i = ch[0],它确实从i开始,但是随后只输入了ijklmno...

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...

我希望它读取h,输出为i,读取e,输出为f,依此类推,直到到达数组末尾为止.

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.

推荐答案

您正在使用循环索引i而不是循环中的第i个字符,这意味着代码的输出不依赖于输入String(很好,除了输出的长度与输入的长度相同).

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).

更改

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

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

这篇关于如何在Java中将数组字符向右移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆