1. int转string(三种方法)
public static void main(String[] args) {
//int -> string
int testInt = 10;
String testString1 = testInt + "";
System.out.println("string1: " +testString1);
String testString2 = String.valueOf(testInt);
System.out.println("string2: " +testString2);
String testString3 = Integer.toString(testInt);
System.out.println("string3: " +testString3);
}
输出结果:
string1: 10
string2: 10
string3: 10
2.0~9的int数字转为char(两种方法)
public static void main(String[] args) {
//int -> char
int testInt = 4;
char testChar1 = (char) (testInt + '0');
System.out.println(testChar1);
//代表10进制
int radix = 10;
char testChar2 = Character.forDigit(testInt, radix);
System.out.println(testChar2);
}
输出结果:
4
4
3.string转int的方法(两种方法)
public static void main(String[] args) {
//string -> int
String testString = "520";
int testInt1 = Integer.parseInt(testString);
System.out.println("int1: " +testInt1);
int testInt2 = Integer.valueOf(testString);
System.out.println("int2: " +testInt2);
}
输出结果为:
int1: 520
int2: 520
4.string转char的方法
public static void main(String[] args) {
// string -> char
String testString = "abcdefg";
//获取某个下标的字符元素
char ch = testString.charAt(0);
System.out.println("ch: " + ch);
//string转 char array
char chArray[] = testString.toCharArray();
System.out.println("ch: " + chArray[0]);
}
输出结果为:
ch: a
ch: a
5. char转int (两种方法)
public static void main(String[] args) {
// char转 int
char ch = '9';
int testInt1 = Character.getNumericValue(ch);
int testInt2 = (int)ch - (int)'0';
System.out.println("int: "+ testInt1);
System.out.println("int: "+ testInt2);
}
输出结果:
int: 9
int: 9
6.char转string方法(四种方法)
public static void main(String[] args) {
// char转 string
char ch = 's';
String testString1 = String.valueOf(ch);
System.out.println("string: "+ testString1);
String testString2 = ch + "";
System.out.println("string: "+ testString2);
String testString3 = Character.toString(ch);
System.out.println("string: "+ testString3);
String testString4= String.valueOf(new char[]{'j', 'a', 'v', 'a'});
System.out.println("string: "+ testString4);
}
输出结果为:
string: s
string: s
string: s
string: java