因为从前台页面上获取到的用户输入,全是字符串类型,所以有必要进行一些转换。
1字符串转成基本数据类型(这些方法分别在8个类里面)
例:
public class Test01 {
public static void main(String[] args) {
// 字符串转int
String str = "12";
int strInt = Integer.parseInt(str);
System.out.println(strInt + 1);
// 字符串转double
String s2 = "12.2";
double s2d = Double.parseDouble(s2);
System.out.println(s2d + 1);
}
}
2基本数值转成字符串(三种方式)
1)基本类型直接与””相连接 (直接与空串连接)
2)调用String的valueOf方法(静态方法)
3)包装类的toString方法
例:
public class Test01 {
public static void main(String[] args) {
//直接加空串
String s1=12+"";
//valueOf方法
String s2=String.valueOf(6.6);
System.out.println(s1+s2);
//toString方法
String s3=Integer.toString(6666);
System.out.println(s3+1);
}
}
3字符串转字节数组:getBytes()方法
public class Test01 {
public static void main(String[] args) {
String str="china";
byte[] bytes=str.getBytes();
for(int i=0;i<bytes.length;i++){
System.out.print(bytes[i]+" ");
}
}
}
4字节数组转字符串:构造方法
例:
public class Test01 {
public static void main(String[] args) {
byte[] bytes = { 65, 66, 67, 68 };
String str = new String(bytes);
System.out.println(str);
byte[] bytes1 = { -65, -66, -67, -68 };
String str1 = new String(bytes1);
System.out.println(str1);
byte[] bytes2 = { 65, 66, 67, 68 };
String str2 = new String(bytes2, 1, 2);
System.out.println(str2);
}
}
5字符串转字符数组:toCharArray()方法
public class Test01 {
public static void main(String[] args) {
String str="china";
char[] ch=str.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]+" ");
}
}
}
6字符数组转字符串:构造方法
public class Test01 {
public static void main(String[] args) {
char[] ch={'中','a','2','A'};
String str=new String(ch);
System.out.println(str);
String str2=new String(ch,0,1);
System.out.println(str2);
}
}
7字符串转字符串数组:split()方法
public class Test01 {
public static void main(String[] args) {
String str = "篮球,足球,排球";
String[] strs = str.split(",");
for (String s : strs) {
System.out.println(s);
}
}
}
6数组转字符串
Arrays工具类的toString方法(是带着数组格式的)
import java.util.Arrays;
public class Test01 {
public static void main(String[] args) {
int[] arr={1,5,6,8,2,3};
String str=Arrays.toString(arr);
System.out.println(str);
}
}
7集合转数组
import java.util.ArrayList;
import java.util.Collection;
public class Test01 {
public static void main(String[] args) {
//创建对象
Collection<String> col=new ArrayList<String>();
//添加元素
col.add("中国");
col.add("你好");
col.add("java");
Object[] strs=col.toArray();
for(int i=0;i<strs.length;i++){
System.out.println(strs[i]+"");
}
}
}
这里Object转成String,还可以这样写: