如何使用Java将字符串中所有的空格移动到前面?
Input string = "move these spaces to beginning"
Output string = " movethesespacestobeginning"
如何使用Java将字符串中所有的空格移动到前面?
Input string = "move these spaces to beginning"
Output string = " movethesespacestobeginning"
试试这个:
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);
使用 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();
}
String
类提供的操作,看看是否有任何有帮助的。http://docs.oracle.com/javase/8/docs/api/java/lang/String.html - ajb