Java数据类型相互转换
1、int和String互转
int i;
String s;
//int转String
s = Integer.toString(i);
s = String.valueOf(i);
s = "" + i;
//String转int
i = Integer.valueOf(s).intValue();
i = Integer.parseInt(s);
2、char[]和String互转
char[] data = { ‘a‘, ‘b‘, ‘c‘ };
//char[]转String
String str1 = new String(data);
String str2 = String.valueOf(data);
//String转char[]
String str3 = "abcdefg";
char[] strArr1 = str3.toCharArray();
3、String[]和String互转
//String转String[]
String str4 = "ab,cd,ef,g";
String[] strArr2 = str4.split(",");
//String[]转String
String[] strArr3 = {"ab","cd","ef","g"}
StringBuffer stringbuffer = new StringBuffer();
for(int i=0;i<strArr3.length;i++) {
stringBuffer.append(strArr[i]);
}
String str5 = stringBuffer.toString();
String的split()方法
public class test {
public static void main(String[] args) {
String s = " hello world ";
String[] strArr = s.split(" ");
for(int i=0;i< strArr.length;i++) {
System.out.println("‘"+strArr[i]+"‘");
}
StringBuilder sb = new StringBuilder();
for(int i=0;i< strArr.length;i++) {
sb.append(strArr[i]);
if(i != strArr.length-1) {
sb.append(" ");
}
}
System.out.println("‘"+sb.toString()+"‘");
}
}
/*
‘‘
‘hello‘
‘world‘
‘ hello world‘
*/
Java数据类型相互转换