Java program to reverse a sentence

Problem

Write a java program to:

  • Reverse a sentence by letters
  • Reverse a sentence by words

Reverse Sentence by letters

Code

  1.  public class Main {
  2.      public static void main(String[] args) {
  3.          String sentence=“Welcome to java”;
  4.          System.out.println(reverseByLetters(sentence));
  5.      }
  6.      public static String reverseByLetters(String sentence){
  7.          char[] c=sentence.toCharArray();
  8.          String out=“”;
  9.          for (int i=c.length1;i>=0;i){
  10.              out+=c[i];
  11.          }
  12.          return out;
  13.      }
  14.  }
  15.  

Output

avaj ot emocleW

Explanation

  • First, we broke the String sentence into characters by calling the toCharArray() function on the string.
  • Then we used a for loop to iterate the characters in reverse and get the final String.

Reverse Sentence by Words

Code

  1. public class Main {
  2.     public static void main(String[] args) {
  3.         String sentence=“Welcome to java”;
  4.         System.out.println(reverseByWords(sentence));
  5.     }
  6.     public static String reverseByWords(String sentence){
  7.         String[] s=sentence.split(” “);
  8.         String out=“”;
  9.         for (int i=s.length1;i>=0;i){
  10.             out+=s[i]+” “;
  11.         }
  12.         return out;
  13.     }
  14. }
  15.  

Output

java to Welcome 

Explanation

  • We broke the sentence at spaces using the string.split(” “) function and stored it in a String array.
  • Then we iterated the array in reverse. We kept on attaching each element of the array together along with space and we got the final result.

Leave a Comment