The Artima Developer Community
Sponsored Link

Java Answers Forum
String to Ascii code

1 reply on 1 page. Most recent reply: Feb 3, 2003 3:04 PM by Charles Bell

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Richard Guerrini

Posts: 2
Nickname: goa
Registered: Jan, 2003

String to Ascii code Posted: Feb 2, 2003 12:55 AM
Reply to this message Reply
Advertisement
How do I convert a String into its corrispondent
Ascii code, I've tried using charCodeAt but
I can't get it to work


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: String to Ascii code Posted: Feb 3, 2003 3:04 PM
Reply to this message Reply
Check out the following link concerning unicode and ascii:

http://java.sun.com/docs/books/jls/first_edition/html/3.doc.html#95413

The first 128 characters of the Unicode character encoding are the ASCII characters.

char is a primitve type of data, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
Ascii is just a subset of unicode.
Read all about unicode at:
http://www.unicode.org/

I think you are just looking for the numeric value of each character in a string.

Use the Character class static method to do this:

public static int getNumericValue(char ch)

Use the charAt(int index) method of the String class to iterate through each character in the string.

Check this out:

public class Test{
    
    public Test(){
        
    }
    
    public static void main (String[] args){
        Test test = new Test();
        test.convert("This is a test.");
    }
    
    public void convert(String s){
        for (int i = 0; i < s.length(); i++){
            char nextCharacter = s.charAt(i);
            int value = Character.getNumericValue(nextCharacter);
            System.out.println("Character: " + String.valueOf(nextCharacter) + " Value: " + String.valueOf(value));
        }
    }
}


This gives the following output:
Character: T Value: 29
Character: h Value: 17
Character: i Value: 18
Character: s Value: 28
Character: Value: -1
Character: i Value: 18
Character: s Value: 28
Character: Value: -1
Character: a Value: 10
Character: Value: -1
Character: t Value: 29
Character: e Value: 14
Character: s Value: 28
Character: t Value: 29
Character: . Value: -1

Flat View: This topic has 1 reply on 1 page
Topic: Running Applet Classes from Packages Previous Topic   Next Topic Topic: Rendering a cell in JTable

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use