3

Possible Duplicate:
ROT-13 function in java?

I have to shift all char from a string 13 places in the alphabet

private static String encode(String line) {
    char[] toEncode = line.toCharArray();
    for (int i = 0; i < toEncode.length; i++) {
        if (Character.isLetter(toEncode[i])) {
            toEncode[i] += 13;
        }
    }
    line = String.valueOf(toEncode);
    return line;
}

The Problem is that for example 'z' get to a ?. How can I solve that?

Thx for help.

Community
  • 1
  • 1
L3p0
  • 95
  • 1
  • 3
  • 8

3 Answers3

5

It is because next chars after 'z' is punctuation chars and so on. You can shift so that 'z' will be 'n' for example.

toEncode[i] = (toEncode[i] + 13 - (int)'a') % 26 + (int)'a';
pepyakin
  • 2,217
  • 19
  • 31
  • 1
    I know that this thread has been on here for quite some time now but I thought it would be worth posting this anyway for future reference. I think that you have a typo in your formula. Should it not be ...% 26... instead of 25 ? Since we want 'z' to shift to 'a' and not to 'b'. – cottonman Dec 06 '16 at 10:47
  • 1
    Oh, yes, you are right. I'm mistakingly assumed that is alphabet consists of 25 letters. – pepyakin Dec 06 '16 at 11:11
0
System.out.println(('z'+ (char)13)); //output -135
System.out.println((char)('z'+ (char)13)); //output - ?
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
  • @ Chandra Sekhar : Thanks for the answer: Please add explanations and guiding instructions for 'homework' questions . – Jayan Apr 06 '12 at 03:33
0

If the calculated char is greater than the last letter (z => 122 or Z => 90) just substract the value of the last letter from the calculated value. You find these numbers all over the internet, e.g. here.

fragmentedreality
  • 1,287
  • 9
  • 31