方法 1:使用 StringBuilder(推荐)
StringBuilder 提供了 setCharAt() 方法,可以直接修改指定位置的字符。

public class ReplaceCharInString {
public static void main(String[] args) {
String original = "Hello, World!";
int index = 7; // 要替换的位置(从0开始)
char newChar = 'J';
// 转换为StringBuilder
StringBuilder sb = new StringBuilder(original);
sb.setCharAt(index, newChar);
String modified = sb.toString();
System.out.println("修改后的字符串: " + modified); // 输出: Hello, Jorld!
}
}
说明:
StringBuilder是可变的,适合频繁修改字符串。index超出字符串长度范围,会抛出StringIndexOutOfBoundsException。
方法 2:使用 substring 拼接
如果不想用 StringBuilder,可以通过 substring 分割字符串并重新拼接。
public class ReplaceCharInString {
public static void main(String[] args) {
String original = "Hello, World!";
int index = 7;
char newChar = 'J';
// 检查索引是否有效
if (index >= 0 && index < original.length()) {
String modified = original.substring(0, index)
+ newChar
+ original.substring(index + 1);
System.out.println("修改后的字符串: " + modified); // 输出: Hello, Jorld!
} else {
System.out.println("索引超出范围!");
}
}
}
说明:
- 适用于少量修改,但多次拼接效率较低。
- 需要手动检查索引有效性。
方法 3:转换为字符数组修改
将字符串转为字符数组,修改后重新组合成字符串。

public class ReplaceCharInString {
public static void main(String[] args) {
String original = "Hello, World!";
int index = 7;
char newChar = 'J';
char[] chars = original.toCharArray();
if (index >= 0 && index < chars.length) {
chars[index] = newChar;
String modified = new String(chars);
System.out.println("修改后的字符串: " + modified); // 输出: Hello, Jorld!
} else {
System.out.println("索引超出范围!");
}
}
}
说明:
- 适合需要多次修改字符数组的情况。
- 同样需要检查索引有效性。
注意事项
- 字符串不可变性:Java 中的
String是不可变的,直接修改字符串会创建新对象。 - 索引范围:确保
index在0到length() - 1之间,否则会越界。 - 性能:
StringBuilder是最高效的方法,尤其适合循环或频繁修改。
替换多个位置的字符
如果需要替换多个位置的字符,可以结合循环或使用 StringBuilder 的 setCharAt():
public class ReplaceMultipleChars {
public static void main(String[] args) {
String original = "abcdef";
int[] indices = {1, 3, 5}; // 要替换的位置
char newChar = 'X';
StringBuilder sb = new StringBuilder(original);
for (int index : indices) {
if (index >= 0 && index < sb.length()) {
sb.setCharAt(index, newChar);
}
}
System.out.println("修改后的字符串: " + sb); // 输出: aXcXeX
}
}
| 方法 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
StringBuilder |
频繁修改或单次修改 | 高效、简洁 | 需要额外对象 |
substring 拼接 |
少量修改且无需额外依赖 | 逻辑直观 | 多次拼接效率低 |
| 字符数组 | 需要多次修改字符数组 | 灵活 | 需要手动检查索引 |
根据实际需求选择合适的方法!

