Ali*_*sar 3 java arrays string shift
这就是我所拥有的:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经将字符串转换为数组,并且已经找到了如何进行移位的方法,但是现在我陷入了困境。
我想要的是从代码开始ch[0],读取字符,将其向右移(hto i),然后对数组中的每个字符执行相同操作,直到到达末尾。
现在,我的代码输出opqrs。我要它输出ifmmp。如果我更换了int i = 0在for带环int i = ch[0],它在启动i,但随后它只是输入ijklmno...
我希望它读取h,输出为i,读取e,输出为等f,直到到达数组的末尾。
您使用循环索引i而不是循环中的ith字符,这意味着代码的输出不依赖于输入String(当然,输出的长度与输入的长度相同)。
更改
char c = (char) (((i - 'a' + 1) % 26) + 'a');
Run Code Online (Sandbox Code Playgroud)
至
char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');
Run Code Online (Sandbox Code Playgroud)