数组和字符串的相互转化

Myth丶恋晨 2024-03-23 23:41 180阅读 0赞

1.数组转字符串

使用 java.util.Arrays 类的 toString() 方法将数组转换为字符串。示例代码如下

  1. String[] array = {"Hello", "World"};
  2. String str = Arrays.toString(array);
  3. System.out.println(str); // 输出: [Hello, World]

使用 String.join() 方法将数组元素连接成字符串。示例代码如下:

  1. String[] array = {"Hello", "World"};
  2. String str = String.join(", ", array);
  3. System.out.println(str); // 输出: Hello, World

2.字符串转数组:

使用 String.split() 方法将字符串拆分为字符串数组。示例代码如下:

  1. String str = "Hello, World";
  2. String[] array = str.split(",");
  3. System.out.println(Arrays.toString(array)); // 输出: [Hello, World]

使用 java.util.ArrayList 类的 toArray() 方法将 List<String> 转换为字符串数组。示例代码:

  1. List<String> list = new ArrayList<>();
  2. list.add("Hello");
  3. list.add("World");
  4. String[] array = list.toArray(new String[0]);
  5. System.out.println(Arrays.toString(array)); // 输出: [Hello, World]

发表评论

表情:
评论列表 (有 0 条评论,180人围观)

还没有评论,来说两句吧...

相关阅读