Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Strings in Java

Options
  • 08-12-2002 4:02pm
    #1
    Registered Users Posts: 23,212 ✭✭✭✭


    Hi All,

    I'm have a fairly basic problem with a Java program I am writing. I have a string (which is read in from the keyboard). I want to get the ASCII value of each member of the string (e.g. A=65, B=66, etc). I am sure it's relativly easy to do.

    I am a getting a little frustrated with searching java.sun.com (22,941 hits for my query).

    Thanks,

    TD.


Comments

  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    From: Java.Sun.com > Java API

    byte[] getBytes()
    Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.


  • Registered Users Posts: 1,186 ✭✭✭davej


    First convert the string to a char[] array using the toCharArray() method. Then you can cast each char in the array to an int using a loop. The int values will correspond to the ascii code...

    davej


  • Registered Users Posts: 21,264 ✭✭✭✭Hobbes


    ASCII? Wouldn't it be Unicode?


  • Registered Users Posts: 23,212 ✭✭✭✭Tom Dunne


    Er, I'm not sure.

    What I'm trying to do is implement ROT13 to encode a message. When the user enters a word, each letter is rotated by 13 characters to A becomes M, B becomes N, etc.

    Pretty basic stuff, but this is my first foray into Java. Give me 8051 assembly language any day.

    TD.


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    I'll try this out myself in a sec......

    But just try

    String.getBytes();

    and for each byte, just add 0xd, then convert it back to a string....

    {edit:

    Yep, do as above, then cast each byte into a char and add to the string. E.g.
    byte[] b;
    String s = "";
    for(int i = 0; i < b.length; i++) {
         s += (char)(b[i] + 0xd);
    }
    

    And hey presto! Spaces always become "?" so you might want to remove them using a tokenizer (or a randomizer)


  • Advertisement
  • Registered Users Posts: 23,212 ✭✭✭✭Tom Dunne


    Thanks Seamus, I'll give it a try within the next few days.


  • Registered Users Posts: 21,264 ✭✭✭✭Hobbes


    I believe you have to use s.charAt() so as to handle Unicode.

    eg.
       String s = "This is a test";
    
       for (int i = 0; i < s.length(); i++)
          char rot = s.charAt(i);
    
          if ((rot >= 'A') & (rot <= 'Z')) {
             System.out.print((char) rot + 13);
          }
       }
    
    

    You get the general idea.


Advertisement