在不使用 replace() 方法的情況下,替換 Java 中字串中的字元
要在不使用 replace() 方法的情況下替換字串中的字元,請嘗試以下邏輯。
假設以下為我們的字串。
String str = "The Haunting of Hill House!";
要將某個位置的字元替換為另一個字元,請使用 substring() 方法登入。在此處,我們將第 7 個位置替換為字元“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); // replacing character at position 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!
廣告