1

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.

7
  • 1
    Think about what happens if you have ch as 'z'? What happens if ascii char value of your character is 256? Commented Oct 11, 2017 at 15:58
  • What do you mean, 'by n'? Commented Oct 11, 2017 at 15:59
  • n is a variable as in first case it is 2 now it is decided at runtime. Commented Oct 11, 2017 at 16:00
  • Note it may be assumed that the input string contains only spaces and Characters from Capital "A" to "Z". Commented Oct 11, 2017 at 16:02
  • since ASCII 'Z' is 90, just test your char if it's > 90 and if so subtract 26 Commented Oct 11, 2017 at 16:03

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just compiled your code and it worked as perfect as could thanks.
Can Accept your answer in 2 minutes and said by SO
2

You have to:

  1. Take your character and remap it to a 0-26 index
  2. Add your increment to that index
  3. Apply a 26 mod to the result
  4. Remap the index back again to ASCII

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'
}

2 Comments

You are a minute late sir can't accept your answer but it helped me and therefore a +1 by me.
ahah next time i’ll post code first and edit with comments later :) happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.