Mahesh Mahesh - 2 months ago 7
Java Question

Move the spaces to the front of the string?

How can we move all the spaces of the String to the front using Java?

Input string = "move these spaces to beginning"

Output string = " movethesespacestobeginning"

Answer

Try this:

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