【问题标题】:Convert string array to strings with a whitespace separating them [duplicate]将字符串数组转换为用空格分隔的字符串[重复]
【发布时间】:2015-06-02 07:04:36
【问题描述】:

我有一个字符串数组(不是数组列表),将它打印成一个用空格分隔它们的新字符串的最佳方法是什么,比如说

String array = {"a", "b", "c"};

我想把它打印到“a b c”,我该怎么做?

【问题讨论】:

  • 使用for循环并对其进行字符串连接操作

标签: java


【解决方案1】:

您可以使用此代码获取带空格的字符串。

String[] array = {"a", "b", "c"};
String output = "";
for (int i = 0; i < array.length; i++) {
    output += array[i] + " ";
}

【讨论】:

    【解决方案2】:

    您可以使用 Arrays.toString(String[])。它将返回一个格式的字符串:

    [a, b, c]
    

    然后您可以简单地将“[”、“]”、“”替换为空字符串,您将只剩下空格:

    String[] str = { "a", "b", "c" };
    System.out.println(Arrays.toString(str).
                  replace("[", "").replace("]","").replace(",", ""));
    

    输出是:a b c

    当然,这仅在您的字符串不包含这些字符之一时才有效!

    【讨论】:

    • 酷。我没有这样想:)
    【解决方案3】:
    public String printOutput(String[] input){
         String output="";
          for(String text :  input){
          output+=" "+text;
          }
       return output;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      相关资源
      最近更新 更多