How to pick up a single character from a string using Java?
For example, "this is yahoo answers"
, from here I want to pick up each single character and convert it into its ASCII val开发者_Python百科ue. How can I do it?
Your question is a bit vague, but probably you meant to want this?
for (char c : "this is yahoo answers".toCharArray()) {
System.out.println((int) c);
}
This produces the following:
116 104 105 115 32 105 115 32 121 97 104 111 111 32 97 110 115 119 101 114 115
Casting the char
to an int
will display its codepoint.
String s = "stackoverflow.com";
for(int i=0; i<s.length(); i++) {
int ascii = (int) s.charAt(i) ;
// .....
}
for(int i = 0; i< theString.length; i++)
theString.charAt(i);
If you want to support the whole unicode range, including for example the emoticons new in 6.0 (http://unicode.org/Public/6.0.0/charts/versioned/U1F600.pdf), you could try this:
for (int i=0, len=string.length(); i<len; ++i) {
int codepoint = Character.codePointAt(string, i);
if (codepoint > Character.MAX_VALUE) {
++i;
}
System.out.println(codepoint);
}
Otherwise, if you are sure that the input will only be ascii, why not state this assumption in the code like this:
byte[] ascii = string.getBytes("US-ASCII");
for (int i=0, len=ascii.length; i<len; ++i) {
int ch = ascii[i];
System.out.println(ch);
}
This should throw a nice exception if the code happens to contain non-ascii characters.
精彩评论