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)
            char ch=s.charAt(i);   //charAt() treats string like an array
            if(ch!=' ')
    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 .
For more java articles ,Click here to Subscribe JavaHungry