سؤال

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.

هل كانت مفيدة؟

المحلول

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));

نصائح أخرى

System.out.println(myString.charAt(i) - '\0');
System.out.println(myString.charAt(i) - 0);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top