替换字符串中的字符

Replacing a char in a string

我正在尝试用 "C" 替换“2”。

String numbers = "99929";
StringBuilder temp = new StringBuilder(numbers);
temp.setCharAt(3, "C");

我收到一条错误消息

I ncompatible type, String cannot be converted to Char.

这是什么意思?对不起,我对此很陌生。感谢您的帮助!

"C"(双引号文字)是 Java 中的字符串,但 setCharAt 接受 char 作为第二个参数,尝试 'C' 而不是 char 文字:

temp.setCharAt(3, 'C');

无法将 String 值分配给字符,它们是不同的类型,苹果和橙子

String numbers = "99929";
StringBuilder temp = new StringBuilder(numbers);
temp.setCharAt(3, 'C'); // THIS LINE IS EDITED 

如您所见,我编辑了您代码的最后一行,将双引号替换为单引号,因为实际上它们的含义不同 对文字使用单引号 chars,对文字使用双引号 Strings.