Java - 用于替换字符串中的字母的递归

use*_*542 6 java string

我完全知道字符串是不可变的,不能改变,可以"editabile" - 哦争议!所以我试图得到它,以便在java 中没有字符串的replace()方法,实现字符串中的特定字符串与另一个字符串切换出来的地方.我希望尽可能简单地执行此操作,而无需导入任何util或使用数组.到目前为止,我已经得到它来改变角色,但它没有正确返回,或者,就是......字符串结束.

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);
}
Run Code Online (Sandbox Code Playgroud)

uni*_*eek 6

这怎么打击你?有趣的尾递归.

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);
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

输出:

C:\>java Demo
hello world, i /m / j/v/ progr/m, how /re you tod/y?
Run Code Online (Sandbox Code Playgroud)


Gen*_*Jam -1

是的,充满鳗鱼的气垫船是正确的。StringBuilder 是你的朋友。它是可变的,您可以将字符串输入 StringBuilder,然后进行交换并在最后调用 toString() 即可完成。