0

I have a loop with i incrementing through a string, and I want to print that character, but its ASCII code.

myString = "90210";
for (int i = 0; i < myString.length(); i++) {
    System.out.println(myString.charAt(i));
}

To output:

57
48
50
49
48

Obviously charAt() doesn't do this, but I need another method to append to it to get my desired result.

gator
  • 3,465
  • 8
  • 36
  • 76

2 Answers2

5

Just cast to an int so that you get the numerical value of the char, which consequently uses the overloaded println(int) method

System.out.println((int)myString.charAt(i));
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0
System.out.println(myString.charAt(i) - '\0');
System.out.println(myString.charAt(i) - 0);
Olayinka
  • 2,813
  • 2
  • 25
  • 43
  • That's a pretty curious way to cast. – Radiodef Mar 09 '14 at 00:24
  • For curious people, this works because a `char (op) char`, where `op` is any of the `+, -, *, /, %` operators, results in an `int` value. This is actually true for all numeric types smaller or equal to an `int`. – Sotirios Delimanolis Mar 09 '14 at 00:27