我们如何使用Java将String的所有空格移到前面?
Input string = "move these spaces to beginning"
Output string = " movethesespacestobeginning"
答案 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();
}