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
- public class Main {
- public static void main(String[] args) {
- String sentence="Welcome to java";
- System.out.println(reverseByLetters(sentence));
- }
- public static String reverseByLetters(String sentence){
- char[] c=sentence.toCharArray();
- String out="";
- for (int i=c.length-1;i>=0;i--){
- out+=c[i];
- }
- return out;
- }
- }
-
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
- public class Main {
- public static void main(String[] args) {
- String sentence="Welcome to java";
- System.out.println(reverseByWords(sentence));
- }
- public static String reverseByWords(String sentence){
- String[] s=sentence.split(" ");
- String out="";
- for (int i=s.length-1;i>=0;i--){
- out+=s[i]+" ";
- }
- return out;
- }
- }
-
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.
0 Comments
Thanks for leaving a comment. I will try to reply you soon.