Recursively reverse string Java - java

I tried to recursively reverse a string in Java, but I am getting just the last character as output.
I looked up online and most of the codes have modified the input string. I am trying to build the output from empty string to reversed string. Please tell me what is wrong in my program.
class reverseStringRecursion
{
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = " Hello I am my name.";
String output = "";
return recursiveHelper(strInput, 0, output);
}
public static String recursiveHelper(String strInput, int index, String output)
{
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
else
output+= recursiveHelper(strInput, index + 1, output) +"";
return output;
}
}
The above code is returning output '.' only and nothing else. PLease help.

Others have done a good job of explaining why your code doesn't work. For comparison, here's a working version with some comments:
public static void main(String args[])
{
System.out.println(reverse("Hello I am my name."));
}
public static String reverse(String text)
{
// Base case:
// If the string is empty, we're done.
if (text.length() == 0) {
return "";
} else {
// reverse("hello") = reverse("ello") + "h"
return reverse(text.substring(1)) + text.charAt(0);
}
}

Since String in Java are immuatable, passing it by parameter is useless on this case, so I removed it.
public class Main {
public static void main(String args[]) {
System.out.println(reverse());
}
public static String reverse() {
String strInput = " Hello I am my name.";
return recursiveHelper(strInput, 0);
}
public static String recursiveHelper(String strInput, int index) {
String output;
if(index == (strInput.length() - 1 )){
output = strInput.charAt(index) + "";
}else{
output = recursiveHelper(strInput, index + 1) + strInput.charAt(index);
}
return output;
}
}
Try it online!

Since strInput always contains the original String, the following condition makes sure your code only takes the last character of that String and ignore all the other characters:
if(index == (strInput.length() - 1 ))
output += strInput.charAt(index) + "";
To build the reversed String recursively, you have to append the last character of the String to the reverse of the sub-string of the first length()-1 characters.
This means that you don't need the 2nd and 3rd arguments of your method, and strInput should be passed a shorter String in each recursive call.
public static String reverse (String strInput)
{
if(strInput.length() <= 1)
return strInput;
else
return strInput.charAt(strInput.length()-1) + reverse (strInput.substring(0,strInput.length()-1));
}

I would change your function recursiveHelper() to only receive one argument (the String that you want to reverse). Using the substring method from Java you can do it like this:
public static String recursiveHelper(String strInput) {
if(strInput.length() == 1) {
return strInput;
}
else if(strInput == "") {
return "";
}
String subString1 = recursiveHelper(strInput.substring(0, strInput.length()/2)); // Here we copy the first half of the String to another String
String subString2 = recursiveHelper(strInput.substring(strInput.length()/2)); // Here we do the same, but with the second half of the original String
return susbString2 + subString1; // It is very important that you sum the two substrings in this order!
}

Modified your class:
public class ReverseStringRecursion {
public static void main(String args[])
{
System.out.println(reverse());
}
public static String reverse()
{
String strInput = "My Name is Jane Doe";
String output = "";
return recursiveHelper(strInput,0);
}
public static String recursiveHelper(String strInput, int index)
{
if(index == (strInput.length() - 1 ))
return "" + strInput.charAt(index) ;
else
return recursiveHelper(strInput,index+1) + strInput.charAt(index);
}
}

public class Main
{
public static void main(String[] args) {
String str1="abc";
String str2="";
for(int i=str1.length()-1;i>=0;i--)
{
str2=str2+Character.toString(str1.charAt(i));
}
System.out.println("After Reverse: "+str2);
}
}

1) Base case
if left>=right - do nothing
2) otherwise swap s[left] and s[right} and call helper(left+1, right-1)].
class Solution {
public void reverseString(char[] s) {
int left = 0, right = s.length - 1;
while (left < right) {
char tmp = s[left];
s[left++] = s[right];
s[right--] = tmp;
}
}
}

Related

How do you capitalize a char in a string using recursion?

I'm currently learning Java recursion for the first time, and am stuck on a problem. The task is to receive a string s and char x, and capitalize the character x if it appears in the string, as well as make all non-x characters lowercase. (i.e. Digging returns diGGinG if x is 'g'). Right now, my code returns "iggingggingGINGINGngg"
I know the code is probably quite flawed, but there aren't many similar recursion problems available and I'm not sure where to start with my mistakes. Any pointers are appreciated.
public class Capitalize {
public static String capitalize(String s, char x) {
if(s.length() == 0) {
return s;
}
String ans = "";
if(s.charAt(0) == x) {
ans += s.substring(1).toUpperCase();
}
else {
ans +=s.substring(1).toLowerCase();
}
return ans + capitalize(s.substring(1), x);
}
public static void main(String[] args) {
System.out.println(capitalize("Digging", 'g')); //return diGGinG
}
}
there is a misunderstanding of the use of substring
System.out.println("Digging".substring(1)); // output : igging
To get the only first element you should use :
System.out.println("Digging".substring(0,1)); // output : D
Try this instead :
public static void main(String []args){
System.out.println(capitalize("Digging", 'g')); // output : diGGinG
}
public static String capitalize(String s, char x) {
if(s.length() == 0) {
return s;
}
String ans = "";
if(s.charAt(0) == x) {
ans += s.substring(0,1).toUpperCase();
}
else {
ans +=s.substring(0,1).toLowerCase();
}
return ans + capitalize(s.substring(1), x);
}

How to print a string letter by letter recursively with a star between each? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to print a String letter by letter with a * between each letter.
I want to find a recursive solution and not an iterative one. The signature must be :
public static String allStar(String a);
Beshambher's answer is a neat and easy way to do it. But if you want to do it recursively then :
public static String allStar(String a) {
if(a == null || a.isEmpty()) {
return "";
}
if(a.length() == 1) {
return a;
}
return a.charAt(0) + "*" + allStar(a.substring(1));
}
Try this where first the string is split into array of strings of each character and then joined together with a * character in between them.
System.out.println(String.join("*", a.split("")));
try this code :
public class Main {
static String Answer = "" ;
public static void main(String[] args) {
Main.SetStarAfterEachLetter("hello!");
System.out.println(Answer);
}
public static void SetStarAfterEachLetter(String letter){
Answer = Answer + letter.charAt(0);
Answer = Answer + " * ";
letter = letter.substring(1);
if(!letter.isEmpty()) {
SetStarAfterEachLetter(letter);
}
}
}
this is more general answer :
import java.util.Scanner;
public class Main {
static String Answer = "" ;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();
Main.SetStarAfterEachLetter(word);
System.out.println(Answer);
}
public static void SetStarAfterEachLetter(String letter){
Answer = Answer + letter.charAt(0);
Answer = Answer + " * ";
letter = letter.substring(1);
if(!letter.isEmpty()) {
SetStarAfterEachLetter(letter);
}
}
Example implementation using overloaded functions addStar(String str) and addStar(int pos, String str):
public static String addStar(String str) {
if (null == str || str.isEmpty()) {
return str;
}
return addStar(0, str);
}
static String addStar(int pos, String str) {
if (pos == str.length() - 1) {
return Character.toString(str.charAt(pos));
}
return str.charAt(pos) + "*" + addStar(pos + 1, str);
}
Tests
System.out.println(addStar(null));
System.out.println("'" + addStar("") + "'");
System.out.println(addStar("a"));
System.out.println(addStar("ab"));
System.out.println(addStar("abcd"));
Output
null
''
a
a*b
a*b*c*d
Solution for recursive print a string
public static void allStar(String a) {
if (a != null && !a.isEmpty()) {
System.out.print(a.charAt(0));
if (a.length() > 1) {
System.out.print('*');
allStar(a.substring(1));
}
}
}
Solution for recursive build a string
public static void allStar(String a, StringBuilder builder) {
if (a != null && !a.isEmpty()) {
builder.append(a.charAt(0));
if (a.length() > 1) {
builder.append('*');
allStar(a.substring(1), builder);
}
}
}
For reducing heap pollution, this one is the best for recursive string build
public static void allStar(String a, int position, StringBuilder builder) {
if (a != null && position < a.length()) {
builder.append(a.charAt(position));
if (++position < a.length()) builder.append('*');
allStar(a, position, builder);
}
}
Use this for print recursivly builded string
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
allStar("test", 0, builder);
System.out.print(builder);
}
Solution with recursions not recommended, but possible for this task.
class AllStar {
public static String allStar(String a){
return allStar(0, a, "");
}
public static String allStar(int ch, String a, String res){
if(a.length() == 0){
return res;
}
if(ch == a.length() - 1){
res += a.charAt(ch);
return res;
}
else{
res += a.charAt(ch) + "*";
return allStar(ch + 1,a,res);
}
}
public static void main(String args[]){
System.out.println(allStar("aritro"));
}
}
Explanation :
We pass in the starting character index in the ch argument. a takes in the String which is to be printed according to the specified format, i.e., with stars. res takes in the String where the result should be stored. The if-statement checks if the letter is the last one. If true, it just appends the letter without a star to the res String as it is specified that stars should be between letters. It also returns the formatted String stored in res. If it is not the last letter, ch is incremented, the original String is passed as it is, and the formatted String is passed on as well. This continues till the last character is reached.

Returning a string that begins at the input parameter index of the String

The Method name is getTheString()
The Return type is String
And the Input parameters is int
I have to return a string that begins at input parameter index position of the String str which is the instance variable. Returns empty string if the input parameter index position is larger than or equal to the string length.
An example would be
If str = “Hawaii”
getTheString(8) returns “ “
getTheString(2) returns
“waii”
I don't know why nothing happens when I execute it or how to fix it could someone help.
public class LoopM
{
public int a, b;
public String str;
public LoopM(){
}
public String getTheString(int f){
str = "Hawaii";
int length = str.length();
for(f = length; f < 10; f++){
return str.substring(f);
}
return str.substring(f);
}
public static void main(String args[]){
//used for testing
LoopM me = new LoopM();
me.getTheString(2);
}
}
Update to this :
public class Test {
public static void main(String[] args) {
System.out.println(getTheString(2));
}
public static String getTheString(int f) {
String str = "Hawaii";
return (f > str.length() || f < 0) ? "" : str.substring(f);
}
}
Output :
waii
You should be using constructor to set value of str field instead of hardcoding it inside getTheString method, also the loop with the return statement inside is a bit strange.
Also you should check if the input parameters are valid (i.e., if str is not null and that f is not negative and less than str.length()
Thus, the code may be improved as follows:
public class LoopM {
public int a, b;
public String str;
public LoopM() {
this("Hawaii");
}
public LoopM(String str) {
this.str = str;
}
public String getTheString(int f) {
int length = null == str? -1 : str.length();
return f > -1 && f < length ? str.substring(f) : "";
}
public static void main(String args[]){
//used for testing
LoopM me = new LoopM();
System.out.printf("\"%s\"%n", me.getTheString(2)); // prints "waii"
System.out.printf("\"%s\"%n", me.getTheString(10)); // prints ""
}
}
The return statement consists of a ternary condition similar to if-else conditions. If the index is greater than the length of the string than it will return " " else it will return substring from the input index
public class Test {
public static void main(String[] args) {
System.out.println("String that begins at 2 index : "+getTheString(2)); // Output waii
System.out.println("String that begins at 8 index : "+getTheString(8));// Output ""
}
public static String getTheString(int index) {
String str = "Hawaii";
return index > str.length() ? "" : str.substring(index);
}
}

Recursive String Parser

I need to create a program that recursively parses a string into smaller substrings. Every substring is one letter shorter than the previous; once it's at the end it would redisplay the word, but with the first letter sliced off, and then substrings of that.
For example: Given the word 'Slugger' the program would display
Slugger
Slugge
Slugg
Slug
Slu
Sl
S
lugger
lugge
lugg
lug
lu
l
And on and on.
This is part of my code so far that is supposed to break things up:
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
return strNew;
} // End removeFirstChar method
I think I've got all the pieces and parts that I need, but perhaps just don't have them in the right order to do what I want.
Any help is greatly appreciated.
Thank you!
I have added the following in your code. See if this works
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
Complete code.....
public class Test {
public static void main(String[] args) {
String str = "slugger";
for(int i=0;i<str.length();i++) {
stringParser(str.substring(i));
}
}
private static void stringParser(String str)
{
if(str.length() < 1)
{
return;
}
else if(str.length() == 0)
{
removeFirstChar(str, 1);
}
else
{
System.out.println(str);
stringParser(str.substring(0, str.length() - 1));
}
} // End stringParser method
private static void removeFirstChar(String str, int i)
{
String strNew = str.substring(i);
stringParser(strNew);
str = strNew;
}
}

Reverse string printing method

I am trying to solve the following problem but how do write the method that accepts String as an argument?
Write a method named printReverse that accepts a String as an
argument and prints the characters in the opposite order. If the empty
string is passed as an argument, the method should produce no output.
Be sure to write a main method that convincingly demonstrates your
program in action. Do not use the reverse method of the
StringBuilder or StringBuffer class!
So far I have solved it in a easier manner:
import java.util.Scanner;
class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: " + reverse);
}
}
I highly recommend you to go through a basic tutorial.
You can simply do:
private static String myReverse(String str) {
String reverse = "";
int length = str.length();
for( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + str.charAt(i);
}
return reverse;
}
And in your main, you simply:
String reversed = myReverse(in.nextLine());
Note that the method is static because you're referring to it from a static manner (main method). If you don't want it to be static, you'll have to access it via an object.
Also note that it's a good practice to always have curly brackets for for loops, even if it contains a single line.
how do write the method that accepts String as an argument?
public static String reverse(String forward) {
char[] strChar = forward.toCharArray();
String reverse = "";
for( int i = strChar.length - 1 ; i >= 0 ; i-- )
reverse = reverse + strChar[i];
return reverse;
}
But for large string appending character with + operator can be inefficient. And reversing string with above approach will result in wrong for uni-code mismatches. As it reverse the code units but not character. There is actually a built-in support available to reverse a string using StringBuilder which works correctly:
public static String reverse(String forward) {
StringBuilder builder = new StringBuilder(forward);
String reverse = builder.reverse().toString();
return reverse;
}
Something like this:
public class StringUtils {
public static String reverse(String forward) {
String result = "";
// Put your code here
return result;
}
}
Using Java 9 you can implement something like this. This code works with both regular characters and surrogate pairs:
public static void printReverse(String str) {
// character code points
str.codePoints()
// character as string
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
// output
.ifPresent(System.out::println);
}
public static void main(String[] args) {
// regular characters
printReverse("lorem ipsum");
// surrogate pairs
printReverse("\uD835\uDD43\uD835\uDD46R\uD835\uDD3C\uD835\uDD44" +
" \uD835\uDD40P\uD835\uDD4A\uD835\uDD4C\uD835\uDD44");
}
Output:
muspi merol
𝕄𝕌𝕊P𝕀 𝕄𝔼R𝕆𝕃
See also: Is there any other way to remove all whitespaces in a string?
Try this:
private static String reverseString(String str) {
String revString = "";
for (int i = str.length() - 1; i >= 0; i--) {
revString = revString + str.charAt(i);
}
return revString;
}
package dowhile;
public class Dowhile {
public static void main(String[] args) {
// TODO code application logic here
String message = "i love java programming";
int msglength = message.length();
int index = msglength - 1;
while (index >= 0) {
System.out.print(message.charAt(index));
index--;
}
}
}
Output:
gnimmargorp avaj evol i
private static void printReverse(String org) {
StringBuffer buffer = new StringBuffer(org);
String reversedStr = buffer.reverse().toString();
System.out.println("The reverse of the string \""
+ str + "\" is \"" + reversedStr + "\".");
}
in the main call the function
printReverse(original);

Categories

Resources