Java将字符串转化为数组
·
将一个字符串转化成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()
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)