在Java中替换字符串中的字符而不使用replace()方法

要在不使用replace()方法的情况下替换字符串中的字符,请尝试以下逻辑。

假设以下是我们的字符串。

String str = "The Haunting of Hill House!";

要将某个位置的字符替换为另一个字符,请使用substring()login方法。在这里,我们将第七个位置替换为字符“ p”

int pos = 7;
char rep = 'p';
String res = str.substring(0, pos) + rep + str.substring(pos + 1);

以下是替换位置7处的字符的完整示例。

示例

public class Demo {
    public static void main(String[] args) {
       String str = "The Haunting of Hill House!";
       System.out.println("String: "+str);
       //替换位置7的字符
       int pos = 7;
       char rep = 'p';
       String res = str.substring(0, pos) + rep + str.substring(pos + 1);
       System.out.println("String after replacing a character: "+res);
    }

输出结果

String: The Haunting of Hill House!
String after replacing a character: The Haupting of Hill House!