Someone on stackoverflow给出了找到字符位置的代码......现在的问题是,它是一个搜索整个字符串并返回每个位置的循环......现在在这段代码中使用了一个示例“pool”。所以它返回 1 和 2
String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
System.out.println(idx);
idx = s.indexOf('o', idx + 1);
}
有没有办法使用方法中返回的两个位置并替换字符...例如,如果我想用 'hh' 替换 'o' 导致 'phhl'
最佳答案
您可能需要检查 public String replaceAll(String regex, String replacement)
String
中的方法。
因此,例如,使用您的代码,您可以执行以下操作:
String s = "pool";
System.out.println(s.replaceAll("o", "h"));
关于java - 如何使用索引循环根据位置替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135351/