“How to modify a specific character in a string in Java?”
In Java, strings are immutable, which means that once a string object is created, its characters cannot be directly modified. However, it is possible to alter a character within a string by using methods such as the StringBuilder class.
Here is an example code using the StringBuilder class to modify a character in a string.
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(1, 'a'); // 将字符串中索引为1的字符修改为 'a'
String newStr = sb.toString();
System.out.println(newStr); // 输出 "Hallo"
By using the setCharAt method of the StringBuilder class, you can modify the character at a specific index position within the StringBuilder object. Finally, calling the toString() method will convert the StringBuilder object to a string.