【问题标题】:Move the spaces to the front of the string?将空格移到字符串的前面?
【发布时间】:2016-04-16 04:46:13
【问题描述】:

我们如何使用Java将String的所有空格移到前面?

Input string  = "move these spaces to beginning"

Output string = "    movethesespacestobeginning"

【问题讨论】:

标签: java string data-structures


【解决方案1】:

试试这个:

String input = "move these spaces to beginning";
int count = input.length() - input.replace(" ", "").length();
String output = input.replace(" ", "");
for (int i=0; i<count; i++) output = " " + output;
System.out.print(output);

【讨论】:

    【解决方案2】:

    使用StringBuilder 提高速度

    public static String moveSpacesToFront(String input) {
        StringBuilder sb = new StringBuilder(input.length());
        char[] chars = input.toCharArray();
        for (char ch : chars)
            if (ch == ' ')
                sb.append(ch);
        for (char ch : chars)
            if (ch != ' ')
                sb.append(ch);
        return sb.toString();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-18
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 2018-08-07
      相关资源
      最近更新 更多