Remove or removing Left and Right whitespaces of String in Java

In every standalone application or web application , One concept is always used that is Username/Password .  Now the problem for the programmer to make sure that the user enters the username or password  string without giving any whitespaces before and after  the characters . If our application is used by bad programmer then he/she will use whitespaces in  username and password , and our application go crashing .

To avoid above problem and many other problems which arises due to whitespaces(before/after) the characters of the string .

So our main goal here is to remove all the white spaces that exists, before the string starts and after the string ends . 

Our goal can be achieved by simply using both left trim and right trim in our code. 

for example :

Original String  :  "   *  Alive is awesome  *  "

After using the below java code

Result  :          "*  Alive is awesome  *"   (Note :  White spaces exists only between the characters of                                                                                        the string )



Pseudo Code for the program :



*  Start from the beginning of the string
*  If  character is whitespace then continue reading string
    else break
*  Index value stores at variable i
* Start another loop  from the end of the string
* If  character is whitespace then continue reading string
   else break
*  Index value stores at variable j
* Print the string starting from index i and ending at index j .


Please click here if you want to remove all the whitespaces in the string  (including whitespaces present in between the string characters)


Demo:


left trim and right trim in the same string





















Code :




public class Alltrim {
    
    static int i,j,k=0;
    
    public static void main(String[] args) {
        alltrim("  * Java     Hungry  *  ");
        
    }
    
    static void alltrim(String s)
    {
        for(i=0;i<s.length();i++)
        {
            char ch=s.charAt(i);
            if(ch!=' ')
            break;
        }
        for(j=s.length()-1;j>=0;j--)
        {
            char ch=s.charAt(j);
            if(ch!=' ')
            break;
        }
        for(k=i;k<j+1;k++)
        System.out.print(s.charAt(k));
    }
    
}

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry