Java中如何替换字符串中指定位置的字符
时间: 2023-06-14 15:04:06 浏览: 1525
在Java中,可以使用String类的charAt()和substring()方法来替换字符串中指定位置的字符。具体步骤如下:
1. 使用charAt()方法获取字符串中指定位置的字符。
2. 使用substring()方法获取需要替换的字符所在位置前后的子字符串。
3. 将需要替换的字符替换成新的字符。
4. 使用加号拼接前后的子字符串和新字符,得到最终的替换后的字符串。
示例代码如下:
```
String str = "hello world";
int index = 6; // 需要替换的字符的位置,从0开始计数
char newChar = 'W'; // 新的字符
String newStr = str.substring(0, index) + newChar + str.substring(index + 1);
System.out.println(newStr); // 输出 "hello World"
```
注意,上述代码中的字符串是不可变的,因此实际上并没有修改原始字符串。如果需要在原始字符串中进行替换,可以将字符串转换为可变的StringBuilder或StringBuffer类型,然后使用setCharAt()方法替换指定位置的字符。
阅读全文
相关推荐














