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

3

如何使用Java将字符串中所有的空格移动到前面?

Input string  = "move these spaces to beginning"

Output string = "    movethesespacestobeginning"

1
你尝试过什么?建议:查看String类提供的操作,看看是否有任何有帮助的。http://docs.oracle.com/javase/8/docs/api/java/lang/String.html - ajb
1
这个IDEONE可以完成这个任务。 - Andreas
使用函数trim()、ltrim()、rtrim()来从两侧、左侧或右侧删除空格。 - Pravin Fofariya
2个回答

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接