How to remove leading and trailing whitespaces from a string
In this shot, we will discuss how to remove leading and trailing whitespaces from a string in Java.
For example, let us consider a string, English.
In this string, there are three spaces at the beginning and two spaces at the end. Our task is to remove those spaces from the string. After we remove the spaces, the string will become English, with no spaces left at the beginning or end.
Solution
We will use the removeSpaces() function. We do not pass any parameters, and the function returns a string without leading and trailing spaces.
Steps
-
Take a string as input.
-
We traverse the string from the start and mark the point as the left index where we get the first character in the string. We do the same thing from the backside and mark the point as the right index.
-
Now, we have the indexes from which the string starts and ends.
-
Finally, we trace out our result string without spaces at the start and end.
Code
Let us look at the code snippet below.
import java.util.Scanner;class removeSpace {static String input = "";public static void main(String[] args) {Scanner scanner=new Scanner(System.in);System.out.println("Enter a string as an input");input = scanner.nextLine();String result = removeSpace.removeSpaces();System.out.println("Our result string without leading and trailing spaces is: "+result);}private static String removeSpaces() {int left=0,right=input.length()-1;while(left<input.length() && input.charAt(left)==' '){left++;}while(right>=0 && input.charAt(right)==' '){right--;}if(left>right){return "";}return input.substring(left,right+1);}}
Enter the input below
Explanation
-
In line 1, we import the
java.util.Scannerclass to read input from the user. -
In line 8, we create a
Scannerobject inside the main function to take the input string from the user, and store that input inString. -
In line 9, we call the
removeSpaces()function, which returns the result string without leading and trailing spaces. -
In lines 15 to 31, we define the
removeSpaces()function. In this function, we initiate two indexes, left and right, and give the values0andstr.length()-1, respectively. -
Then, we run a
whileloop to get the left-most character index of the string. We do this again to get the right-most character index of the string. -
In lines 26 to 31, we can trace out the resultant string that we want, according to the left and the right index. The return value is the string without leading and trailing spaces.