我完全意识到字符串是不可变的,不能改变,可以是“editabile” - 哦争议!所以我试图让没有用于java中字符串的replace()方法,以实现字符串中特定字符与另一个字符交换的位置。我想尽可能简单地做到这一点,而不需要导入任何util或使用数组。到目前为止,我已经得到它来改变字符,但它没有正确返回,或者,那是...字符串结束。Java - 递归替换字符串中的字母
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);
}
使用StringBuilder,因为它就是它的用途。这样做没什么奇怪的,事实上它比递归更清洁简单。 –
你想修改现有的字符串还是从现有的字符串创建一个新的字符串? – Kakarot
在你的return语句中,你最终创建了一个不符合你提到的要求的String实例。 – Kakarot