数组和字符串的相互转化
1.数组转字符串
使用 java.util.Arrays
类的 toString()
方法将数组转换为字符串。示例代码如下
String[] array = {"Hello", "World"};
String str = Arrays.toString(array);
System.out.println(str); // 输出: [Hello, World]
使用 String.join()
方法将数组元素连接成字符串。示例代码如下:
String[] array = {"Hello", "World"};
String str = String.join(", ", array);
System.out.println(str); // 输出: Hello, World
2.字符串转数组:
使用 String.split()
方法将字符串拆分为字符串数组。示例代码如下:
String str = "Hello, World";
String[] array = str.split(",");
System.out.println(Arrays.toString(array)); // 输出: [Hello, World]
使用 java.util.ArrayList
类的 toArray()
方法将 List<String>
转换为字符串数组。示例代码:
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
String[] array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array)); // 输出: [Hello, World]
还没有评论,来说两句吧...