任务是:编写静态函数来操作并返回String
s
public static String tr(String s, String from, String to)
此方法返回一个 String
,其中 from
中存在的 s
中的所有字符都被相应的字符(在相同位置)替换) 字符从 到
。为了使这一点有意义,from
中的所有字符都必须不同,并且 from
和 to
的长度应该相同。例如,如果 from
是“abc”,to
是“XXY”,则所有出现的“a”和“b”都应替换为“X”和“c' by 'Y'。
结果
System.out.println(tr("November 2016", "abcdefghijklmnopqrstuvwyz", "ABCDEFGHIJKLMNOPQRSTUVWYZ"));
System.out.println(tr("abcXYZ","aZcX","||Cx"));
应分别为 2016 年 11 月和 |bCxY|。
这是我的代码。我什至无法正确编译它。有人可以看一下并帮助我吗?
public static String tr(String s, String from, String to) {
for (int i = 0; i < s.length(); i++) {
if s.charAt(i) == from.charAt(i) {
s = s.replace(s.charAt(i), to.charAt(i));
}
}
return s;
}
最佳答案
您的 if 语句需要括号
if (s.charAt(i) == from.charAt(i))
注意已检查您的逻辑
你的逻辑应该是
for (int i = 0; i < s.length(); i++) {
int idexof = from.indexOf(s.charAt(i));
if (idexof != -1) {
s = s.replace(s.charAt(i), to.charAt(idexof));
}
}
return s;
关于java - 替换字符串中的相应字符(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59366771/