Reverse A Sentence In Java Without Using String Functions
Last Updated : Mar 11, 2024
IN - Java | Written & Updated By - Ashish
In this article we will show you the solution of reverse a sentence in java without using string functions, a string class's charAt() method returns the character at the specified position given an index.
Each index in the new string revString is invoked, along with the character at the given position.
All characters returned by charAt() method will be added to the revString string.
After completing the for loop, the revString string will be having the reversed string.
Ideally, this is a very optimal and good solution. Here we will be calling a method printReverse() from the same method based on a condition. This condition is controlled by if condition.
This is to avoid the for loop and use the core programming efficient concept.
If you do not write a good condition in if to stop the recursive call, then it will be calling continuously printReverse method.
This is the drawback of recursive. If you are confident then you can apply recursion logic on any program.
This is a third approach to solve this problem but just another way not to use the String reverse method.
Some of the interviewers may not accept this solution. StringBuilder class is a mutable and final class. This provides a method to reverse its content.
Step By Step Guide On Reverse A Sentence In Java Without Using String Functions :-
package com.java.talkerscode.string.reverse; public class TalkersCode{ public static void main(String[] args) { String str = "TalkersCode"; String revString = ""; for (int i = str.length() - 1; i >= 0; --i) { revString += str.charAt(i); } System.out.println(revString); } }
- First we define a package as packagecom.java.talkerscode.string.reverse.
- Then we create class as TalkersCode.
- Then we define public static void main.
- Then we define The For loop loops from j=string length to j>0.
- It prints this same character of a string at index (i-1) and then returns the reverse of the a string.
- Define an empty String reverse. This is the place we'll put with us final reversed string.
- Interpolate through the array from the last indicator to the first index using a for a loop.
- While iterating, add a character to String reverse.
Conclusion :-
A good method is to write a recursive program to reverse a string. This is done to avoid by using the string reverse() method as well as the for loop.
Because for loop indicates that users are using the most fundamental programming concepts. It's better to take a recursive approach as well as properly explain to them.
I hope this article on reverse a sentence in java without using string functions helps you and the steps and method mentioned above are easy to follow and implement.