How to right trim a String in Java : Source code with example

To remove the unnecessary right  spaces in the beginning of the word  ,also known as right trimming of the word.
Java provides the built in method to right trim the word . But here we are writing the code without using the built in method of java .
for example :
If the user inputs a string like this :  "   Alive is awesome  " , then the result will remove the spaces after the last character of the string .
So the answer will be : "   Alive is awesome"



Demo :



right trim a string in java



















Code : 



public class StringRightTrim
{
    static int i,c=0,res,j;
    
    static void rtrim(String s)
    {
        for(i=s.length()-1;i>=0;i--)
        {
            char ch=s.charAt(i);   //charAt() treats string like an array
            if(ch!=' ')
            break;
        }
        for(j=0;j<i+1;j++)
        System.out.print(s.charAt(j));
    }
    
    
    
    public static void main (String args[])
    {
        
        System.out.println("Original String is : ");
        System.out.println("   manchester united is also known as red devil   ");
        
        StringRightTrim.rtrim("   manchester united is also known as red devil    ");
    }
}

About The Author

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