问题
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 i
th 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