将空格移动到字符串的前面?

时间:2016-04-16 04:46:13

标签: java string data-structures

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

Input string  = "move these spaces to beginning"

Output string = "    movethesespacestobeginning"

2 个答案:

答案 0 :(得分:4)

试试这个:

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);

答案 1 :(得分:0)

使用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();
}