-1

I want to add the letters "ç," "ğ," "ı," "ö" and "ü" into this encrypter's alphabet, and maybe special chars, too. How can I do that?

    for (int i = 0; i < metin.length(); i++) {
        char harf = metin.charAt(i);
        if       (harf >= 'a' && harf <= 'm') harf += i;
        else if  (harf >= 'A' && harf <= 'M') harf += i;
        else if  (harf >= 'n' && harf <= 'z') harf -= i;
        else if  (harf >= 'N' && harf <= 'Z') harf -= i;
        System.out.print(harf);
    }
Pops
  • 30,199
  • 37
  • 136
  • 151
  • 1
    This question is not about Java. Decide what you want your cipher to look like and the Java code to do it will be obvious. – Marko Topolnik Nov 14 '12 at 12:41
  • 3
    That's not caesar or Rot13. It's not reversible(for `i == 1` `harf=='k'` and `harf=='n'` result in the same output) and it has no key. So it's not even encryption. – CodesInChaos Nov 14 '12 at 12:41
  • rot13 used for 26 letters, you will have 31 letters, 31 is not even. – Juvanis Nov 14 '12 at 12:43
  • I only want to know how to expanding this alphabets with this algorithm. Is it possible or not? But i've got my answers so thanks for your "supportive" comments. –  Nov 14 '12 at 12:57

2 Answers2

2

You are using the Java intern Char's as ints to implement the cipher. A better way would be to use a String charSet = "abcdefgh.... %&/(öäüô"; with the chars you want in you charSet.

String charset = "abcdefghijklmnopqrstuvwxyzäöü";    
for (int i = 0; i < metin.length(); i++) {
    int j = charset.indexOf(metin.charAt(i));
    if(j < -1)
    {
        //deal with unknown char
    }
    if(j == charset.length)
    {
        j=0;
    }
    System.out.print(charset.charAt(j+1);
}

I hope you get the idea.

Matt
  • 74,352
  • 26
  • 153
  • 180
nukebauer
  • 321
  • 1
  • 3
  • 1
    For any practical usage this is horribly inefficient. See Peter Lawrey's [answer](http://stackoverflow.com/a/13379261/18573) below for a much better approach. – Miserable Variable Nov 17 '12 at 17:28
1

You can make the strategy more general like this.

String text = "abcdefghijklmnopqrstuvwxyz0123456789!$%^&*()äöü";

for (int i = 0; i < text.length(); i++) {
    char ch = text.charAt(i);
    ch--;
    if (ch % 32 < 13)
        ch += 13;
    else if (ch % 32 < 26)
        ch -= 13;
    else if (ch % 32 < 29)
        ch += 3;
    else
        ch -= 3;
    ch++;
    System.out.print(ch);
}

prints

nopqrstuvwxyzabcdefghijklm#$%&'()*+,.12[3756ñéÿ
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130