Conversion between String and other data types
1. Conversion between String and basic types
1. Convert String to basic data type
For example: Interger.parseInt(String s); this method can convert a string composed of "numeric" characters into integer data.
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. Convert basic types into String data
Use the String.valueOf(); method to convert other types of data into string type data.
Note: Char type data cannot be converted.
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. Convert String model data into character array type (char[])
public char[] toCharArray();
This method stores all the characters of the string in a character array.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
Provides a method to store strings within a specified index range into an array.
public interface InterviewTest3 {
public static void main(String[] args) {
String s1 = "abc123";
char[] ch1 = s1.toCharArray();
}
4. Convert character array (char[]) type to String type
Convert through the constructor of the String class.
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. Convert String to Byte array
Converted through String's getByte() method.
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. Convert Byte array to String type
Call the String constructor to implement conversion.
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
}
}