String与其他数据类型的相互转换
一、String与基本类型的转换
1、String转化为基本数据类型
例如:Interger.parseInt(String s);这个方法可以将“数字”字符组成的字符串转化为整型数据。
public class InterviewTest {
public static void main(String[] args) {
//注意Character没有parseCharacter方法
String str = "1234";
//String类型的数据转换为int类型的数据
int num1 = Integer.parseInt(str);
System.out.println(num1);
// String类型的数据转换为Byte类型的数据,注意byte类型值的范围
// int num2 = Byte.parseByte(str);
// System.out.println(num2);
//
// String类型的数据转换为Short类型的数据,注意Short类型所表示的值的范围
// int num3 = Short.parseShort(str);
// System.out.println(num3);
//String类型的数据转换为long类型的数据,注意long类型所表示的值的范围
long num4 = Long.parseLong(str);
System.out.println(num4);
//String类型的数据转换为float类型的数据,注意float类型所表示的值的范围
float num5 = Float.parseFloat(str);
System.out.println(num5);
//String类型的数据转换为double类型的数据,注意double类型所表示的值的范围
double num6 = Double.parseDouble(str);
System.out.println(num6);
boolean num7 = Boolean.parseBoolean(str);
System.out.println(num7);//false
}
2、基本类型转化为String型数据
使用String.valueOf();方法可以将其他类型的数据转化为字符串类型的数据。
注:不能转化char类型数据。
public class InterviewTest2 {
public static void main(String[] args) {
//将int类型的数据转换为String类型的数据
int i = 1234;
String s1 = String.valueOf(i);
System.out.println(s1);
//将float类型的数据转换为String类型的数据
float f = 0.1f;
String s2 = String.valueOf(f);
System.out.println(s2);
//将boolean类型的数据转换为String类型的数据
boolean bool = false;
String s3 = String.valueOf(bool);
System.out.println(s3);
}
3、String型号数据转化为字符数组类型(char[])
public char[] toCharArray();
这个方法将字符串的全部字符存放在一个字符数组中。
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
提供了将指定索引范围内的字符串存放到数组中的方法。
public interface InterviewTest3 {
public static void main(String[] args) {
String s1 = "abc123";
char[] ch1 = s1.toCharArray();
}
4、字符数组(char[])类型转化为String类型
通过String类的构造器进行转化。
public class InterviewTest4 {
public static void main(String[] args) {
char[] ch = {'a','b','c','1','2','3'};
String s1 = new String(ch);
System.out.println(s1);
}
5、String转化为Byte数组
通过String的getByte()方法转化。
public class InterviewTest5 {
public static void main(String[] args) {
String str = "123abc";
byte[] b = str.getBytes();
for (int i = 0; i <b.length ; i++) {
System.out.print(b[i]+"\t"); //输出结果为:49 50 51 97 98 99
//是每个字符对应的ASCⅡ码
}
}
6、Byte数组转化为String类型
调用String的构造器实现转化。
public class InterviewTest6 {
public static void main(String[] args) {
byte[] b = {49,50,51,97,98,99};
String s = new String(b);
System.out.println(s.toString()); //结果为123abc
}
}