Home > Java > javaTutorial > How to convert string array to comma separated string in Java

How to convert string array to comma separated string in Java

PHPz
Release: 2023-04-27 11:49:08
forward
4860 people have browsed it

Usually written like this:

public static void main(String[] args) {
    String strs = "";
    String[] arr = new String[]{"aa", "cc", "bb"}; // 转换前的字符串数组
    StringBuilder sb = new StringBuilder();
    for (String ele : arr) {
      if (sb.length() > 0) {
        sb.append(",");
      }
      sb.append(ele);
    }
    strs = sb.toString(); // 转换后的逗号分隔字符串
    System.out.println(strs);
}
Copy after login

Simpler way of writing:

public static void main(String[] args) {
    String[] arr = new String[]{"aa", "cc", "bb"}; // 转换前的字符串数组
    String strs = String.join(",", arr); // 转换后的逗号分隔字符串
    System.out.println(strs);
}
Copy after login

The above is the detailed content of How to convert string array to comma separated string in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template