2014年5月13日星期二

char, int, string相互转换

char to int:
Character.getNumericValue(char c)

String to int:
Integer.parseInt(String s)

int to StringBuilder

s.append(int i);

string to char:

s.charAt();

char to string:

You can use Character.toString(char). Note that this method simply returns a call to String.valueOf(char), which also works.
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
But this compiles down to:
String s = new StringBuilder().append("").append('s').toString();
which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16), only for that array to be defensively copied by the resulting String.
String.valueOf(char) "gets in the back door" by wrapping the char in a single-element array and passing it to the package private constructor String(int, int, char[]), which avoids the array copy.

String stringValueOf = String.valueOf('c');

String characterToString = Character.toString('c');

String characterObjectToString = new Character('c').toString();

String concatBlankString = 'c' + "";

String fromCharArray = new String(new char[]{x});

没有评论:

发表评论