Java - Recursion to replace letter in string
java, string
Solution
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?
Problem
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); } ```