Categories

How to reverse a string in Java

 In this problem we are given a string e.g Hello and we need to write a function that will reverse the string and return olleH.

In the below function reverseWords we take a string and read each character from the opposite direction then concatenate each charaters to make the string and finally return the string. 

class ReverseString
{
    
    // str: input string
    public static String reverseWords(String str)
    {
        String s="";  
        // Reverse the string str
        for(int i=str.length()-1; i>=0; i--){
            char ch=str.charAt(i);  
            s+=ch;
        }
        
        return s;
        
    }
}
adbanner