软件编程
位置:首页>> 软件编程>> java编程>> Java将字符串转化为数组的两种方法

Java将字符串转化为数组的两种方法

作者:逐渐霄化  发布时间:2021-07-07 20:33:49 

标签: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]

不会删掉所给字符串的空格

附:java split()方法介绍

split() 方法可以根据匹配给定的正则表达式来拆分字符串。

注意: . 、 | 和 * 等转义字符,必须得加 \。多个分隔符,可以用 | 作为连字符。

语法结构:public String[] split(String regex, int limit)

参数介绍:

  • regex -- 正则表达式分隔符。

  • limit -- 分割的份数。

示例:// 字符串转数组 java.lang.String

String str = "0,1,2,3,4,5";
String[] arr = str.split(","); // 用,分割
System.out.println(Arrays.toString(arr)); // [0, 1, 2, 3, 4, 5]

来源:https://blog.csdn.net/weixin_55519918/article/details/127547325

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com