Reputation: 80
I want to write a program which will take a String and add 2 to every character of the String this was quite simple Here is my code. Example:-
String str="ZAP YES";
nstr="BCR AGU" //note Z=B and Y=A
String str=sc.nextLine();
String nstr=""
for(int i=0;i<str.length();i++)
{
char ch=sc.charAt(i);
if(ch!=' ')
{
if(ch=='Z')
ch='B';
else if(ch=='Y')
ch='A';
else
ch=ch+2;
}
nstr=nstr+ch;
}
Now I want to increase every character by n(instead of 2) and this really I could not solve.
I might think of using n%26 ,and use a loop for conditions but I was not able to solve it how to implement that.
Upvotes: 1
Views: 1382
Reputation: 312106
You have the right idea with using % 26
. The missing piece is that your range isn't zero-based. You can simulate a zero-based range by subtracting 'A' (i..e, treating 'A' as 0, 'B' as 1, etc), and then readding it:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ') {
ch = (char)((ch - 'A' + n) % 26 + 'A');
}
nstr += ch;
}
Upvotes: 3
Reputation: 4378
You have to:
Example:
public static char increment(char c, int n) {
return (char) (((c - 'A') + n) % 26 + 'A');
}
public static void main(String[] args) {
System.out.println(increment('Z', 1)); // returns 'A'
System.out.println(increment('Z', 2)); // returns 'B'
}
Upvotes: 2