Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

How to remove leading and trailing whitespaces from a string

Vinisha Maheshwari

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.Scanner class to read input from the user.

  • In line 8, we create a Scanner object inside the main function to take the input string from the user, and store that input in String.

  • 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 values 0 and str.length()-1, respectively.

  • Then, we run a while loop 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.

RELATED TAGS

communitycreator
java
RELATED COURSES

View all Courses

Keep Exploring