Java将字符串转化为数组
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
将一个字符串转化成String[]数组提供两种方法
前言
将字符串转化成数组提供两种方法
1.split("");
2.toCharArry()方法;
一、使用split()方法
将String s转化为String数组
public class T1 {
public static void main(String[] args) {
String str="abcdefg";
String[] a=str.split("");
System.out.println(Arrays.toString(a));
}
}
>:[a, b, c, d, e, f, g]
public class T1 {
public static void main(String[] args) {
String str="a bc de g";
String[] a=str.split(" ");
System.out.println(Arrays.toString(a));
}
}
>:[a,bc,de,g]
如果要使用多个标记隔开时使用|
public class T1 {
public static void main(String[] args) {
String str="a@bc de g";
String[] a=str.split("@| ");
System.out.println(Arrays.toString(a));
}
}
>:[a, bc, de, g]
二、使用toCharArry(方法
将String s转化为Char数组
public class T1 {
public static void main(String[] args) {
String str="ab cd efg adf";
char[] a=str.toCharArray();
System.out.println(Arrays.toString(a));
}
}
>:[a, b, , c, d, , e, f, g, , a, d, f]
不会删掉所给字符串的空格
总结
将字符串转化为Sting数组时可以使用split()
将字符串转化为char数组时可以使用toCharArry()