user2958542
user2958542

Reputation: 341

Java - Recursion to replace letter in string

I am full aware that strings are immutable and can't be changed and can be "editabile" - ohhh the controversy! So I am trying to get it so that without the replace() method for strings in java, to implement where a specific char in a string gets switched out with another char. I want to do this as simply as possibly without needing to import any util or use arrays. thus far, I've gotten it to change the character, but it's not returning correctly, or, that is... the string ends.

public static void main(String[] args) {
    String words = "hello world, i am a java program, how are you today?";
    char from = 'a';
    char to = '/';

    replace(s, from, to);
}
public static String replace(String s, char from, char to){
    if (s.length() < 1)
        return s;
    if (s.charAt(0) == from) {
        s = to + s.substring(1);
    }
    System.out.println(s);
return s.charAt(0) + replace(s.substring(1, s.length()), from, to);
}

Upvotes: 8

Views: 24555

Answers (7)

Rajeev
Rajeev

Reputation: 1196

It looks like I've a very simple answer

public class Replacer {
    public static void main(String args[]) {
          String words = "hello world, i am a java program, how are you today?";
    char from = 'a';
    char to = '/';

    //String ss = words.replace(from, to);
    System.out.println(words);
    String ss = replace(words, from, to);// recieveing String from replace()
    System.out.println("New Replace String is =>  "+ss );
    }

    
    public static String replace(String s, char from, char to)
    {
        int pos = s.indexOf(from);
        
        // If not found, return the string as such
        if (pos < 0)
        {
            return s;
        }
        
        // Split the string by 'from' and join with 'to'
        return s.substring(0, pos) + to + replace(s.substring(pos+1), from, to);
    }
}

Upvotes: 0

rahulpatil017
rahulpatil017

Reputation: 1

 public String changeXY(String str)
    {
        if (string.IsNullOrEmpty(str)) return str;           
        if(str[0] == 'x')
        {
            return 'y' +  changeXY(str.Substring(1,str.Length - 1));
        }
        else
        {
            return str[0] +  changeXY(str.Substring(1, str.Length - 1));
        }
    }

Upvotes: -1

Rishi Dwivedi
Rishi Dwivedi

Reputation: 928

 Try this code work for u enjoy it
   public static void main(String[] args) {
    String words = "hello world, i am a java program, how are you today?";
    char from = 'a';
    char to = '/';

    //String ss = words.replace(from, to);
    System.out.println(words);
    String ss = replace(words, from, to);// recieveing String from replace()
    System.out.println("New Replace String is =>  "+ss );
    }

public static String replace(String s, char from, char to){
    if (s.length() < 1)
        return s;
         for(int i=0;i<s.length();i++){
        if (s.charAt(i) == from) {
            s = s.substring(0, i)+to + s.substring(++i);
            System.out.println(s);
            return replace(s, from, to);//calling replace()
        }
    }
    return s;
}

*Output is * New Replace String is => hello world, i /m / j/v/ progr/m, how /re you tod/y?

Upvotes: 4

unigeek
unigeek

Reputation: 2826

How does this strike you? Fun with tail recursion.

public class Demo {

  public static void main(String[] args) {
    String words = "hello world, i am a java program, how are you today?";
    char from = 'a';
    char to = '/';

    System.out.println(replace(words, from, to));
  }

  public static String replace(String s, char from, char to){
    if (s.length() < 1) {
      return s;
    }
    else {
      char first = from == s.charAt(0) ? to : s.charAt(0);
      return first + replace(s.substring(1), from, to);
    }
  }

}

Output:

C:\>java Demo
hello world, i /m / j/v/ progr/m, how /re you tod/y?

Upvotes: 10

ErstwhileIII
ErstwhileIII

Reputation: 4843

You can work this by using the "charAt" method for String an putting appropriate characters into a StringBuffer and then running "toString" on the StringBuffer

public class Replacement {
public static void main(String[] args) {
    String words = "hello world, i am a java program, how are you today?";
    char from = 'a';
    char to = '/';

    String changed = replace(words, from, to);
    System.out.println(words);
    System.out.println(changed);
}

public static String replace(String s, char from, char to) {
    StringBuffer result = new StringBuffer(s.length());

    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == from) {
            result.append(to);
        } else {
            result.append(s.charAt(i));
        }
    }
    return result.toString();

}

}

Upvotes: 2

steven0529
steven0529

Reputation: 1563

You can use the Java predefined class StringBuilder. It is more effective than concatenating and manipulating Strings directly. StringBuilder also has a replace() method to cater your problem. See documentation StringBuilder#replace

Upvotes: 0

GenericJam
GenericJam

Reputation: 3015

Yes, Hovercraft Full of Eels is correct. StringBuilder is your friend. It is mutable, you can just feed your String into StringBuilder and then do your swapping and call toString() at the end and your done.

Upvotes: -1

Related Questions