Reverse a sentence in Java
In this post, you will learn how to reverse a sentence using the Java programming language.
Logic in programming is a fundamental key to being a decent developer. Reverse string programming is frequently asked in Java coding tests and interviews. In Java, a string is an object that represents a sequence of characters, which in turn form sentences. Reversing a sentence means reversing the order of the words. Here, we have mentioned different ways to reverse a string in Java.
Reverse a sentence in Java using while loop
In the given Java program, we ask the user to enter sentence and store them in a variable. Then, we use the while loop to extract the word and reverse the sentence with the help of indexOf() and substring() methods.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner sc =new Scanner(System.in);
// getting input from user
System.out.print("Enter a sentence: ");
String str = sc.nextLine();
//Append whitespace for the extraction of last word
str += " ";
String rev_string = "";
// loop through it and print it turn around
while(str.indexOf(" ") != -1){
//Extract word
int indx = str.indexOf(" ");
String word = str.substring(0, indx);
//Concatenate in reverse order
rev_string = word + " "+ rev_string;
//Remove word from the sentence
str = str.substring(indx+1);
}
System.out.print("Reverse String: ");
System.out.println(rev_string);
}
}
Output of the above code:
Enter a sentence: Welcome to etp
Reverse String: etp to Welcome
Reverse a sentence in Java using recursion
A recursion function is a function that is called by itself. In the given Java program, we call the recursion function to get the reverse of a given string. A recursion function continues until some condition is met to prevent it. That's why we use the if statement to break the infinite recursion.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in =new Scanner(System.in);
//Input sentence
System.out.print("Enter a Sentence: ");
String str = in.nextLine();
// Reverse the sentance
// by calling the recursive method
String rev_string = reverse_string(str);
// display the reversed word
System.out.print("Reversed Sentence: ");
System.out.println(rev_string);
}
public static String reverse_string(String str){
int idx = str.indexOf(" ");
//when str has only one word
if(idx == -1)
return str;
return reverse_string(str.substring(idx+1)) +" "+ str.substring(0, idx);
}
}
Output of the above code:
Enter a Sentence: This is a cat
Reversed Sentence: cat a is This
Reverse a sentence in Java using for loop
In the given example, first we ask the user to provide a string input. Then, we get the length of the string and iterate through it using the for loop, and printing the string in reverse order.
import java.util.Scanner;
public class ReverseString
{
public static String rev_string(String str)
{
String[] words = str.split("\\s");
String rev_string = "";
for(int i = words.length-1; i >= 0; i--)
{
rev_string = rev_string + words[i] + " ";
}
return rev_string;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Input String: ");
String str = sc.nextLine();
System.out.println(str);
String reversed_str = rev_string(str);
System.out.println("Output String : "+reversed_str);
sc.close();
}
}
Output of the above code:
Enter Input String:
Welcome to etp
Output String : etp to Welcome
Reverse a sentence in Java using Regular Expression
In the given example, we reverse a string in Java without using the in-built string function.
import java.util.regex.Pattern;
public class ReverseString {
// Method to reverse string
static String reverseString(String str)
{
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("\\s");
// splitting string with a pattern
// and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterating and getting string in reverse order
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args)
{
String str1 = "Welcome to etutorialspoint";
System.out.println(reverseString(str1));
String str2 = "keep learning keep growing";
System.out.println(reverseString(str2));
}
}
Output of the above code:
etutorialspoint to Welcome
growing keep learning keep
Related Articles
Sort array in ascending order JavaAutomorphic number in Java
Pascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java