花花_新世界
从【程序猿】到【程序员】的进化历程
posts - 60,comments - 10,views - 11万

1.字符串转数组

使用Java split() 方法

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

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

// 字符串转数组  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]

2.数组转字符串

方法一: 遍历

String[] arr = { "0", "1", "2", "3", "4", "5" };
// 遍历
StringBuffer str5 = new StringBuffer();
for (String s : arr) {
    str5.append(s);
}
System.out.println(str5.toString()); // 012345

方法二: 使用StringUtils的join方法

//数组转字符串 org.apache.commons.lang3.StringUtils
String str3 = StringUtils.join(arr); // 数组转字符串,其实使用的也是遍历
System.out.println(str3); // 012345
String str4 = StringUtils.join(arr, ","); // 数组转字符串(逗号分隔)(推荐)
System.out.println(str4); // 0,1,2,3,4,5

方法三: 使用ArrayUtils的toString方法

// 数组转字符串 org.apache.commons.lang3.ArrayUtils
String str2 = ArrayUtils.toString(arr, ","); // 数组转字符串(逗号分隔,首尾加大括号)
System.out.println(str2); // {0,1,2,3,4,5}

3.将逗号分隔的字符串转换为List

复制代码
// 将逗号分隔的字符串转换为List
String str = "a,b,c";
// 1.使用JDK,逗号分隔的字符串-->数组-->list
List<String> result = Arrays.asList(str.split(","));
// 2.使用Apache Commons的StringUtils
List<String> result1 = Arrays.asList(StringUtils.split(str, ","));
// 3.通过遍历
String[] strings = str.split(",");
List<String> result2 = new ArrayList<String>();
for (String string : strings) {
    result2.add(string);
}
复制代码

4.将List转换为逗号分隔的字符串

复制代码
// 将List转换为逗号分隔的字符串
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
// 1.使用Apache Commons的StringUtils
String str1 = StringUtils.join(list.toArray(), ",");
// 2.通过遍历
StringBuffer str2 = new StringBuffer();
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = (String) iterator.next();
    str2.append(string);
    if(iterator.hasNext()){
        str2.append(","); 
    }
}
复制代码
posted on   花花_新世界  阅读(4671)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多