• Yogeeta Paryani

JAVA| Program to Reverse a String

This program going to reverse every word of string and give reversed string as an output.

For example, if we input string as "Hello" then the output will be: "olleH".

In this program,we are going to use toCharArray() method which converts the string into character array and the length of newly created array is similar to the length of string.


Step by step explanation:


1. Create class 'Reverse' then under main method declare the string you have to reverse:

class Reverse
{
      public static void main(String args[])
     {
         String str ="Welcome To Programmers Door!!";

2. Create a Character array using your String:

         Char[] c=str.toCharArray();

3. Create an empty array. We are going to use this to store our reversed String:

         String rev="";

4. Create a for loop to iterate character array in reverse order. In the for loop,fill the reverse string 'rev' with the ith element of the character array 'c':

         for(int i=c.length-1;i>=0;i--)
       {
           rev=rev+c[i];
       }   

5.Print the reverse string 'rev':

        System.out.println(rev);
      }
   }  

Output:


!!rooD sremmargorP oT emocleW

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #Java #learn #String #Methods #programming






47 views

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door