StringBuffer sb=new StringBuffer("A");
现在增加我在下面编写的代码中的字母 A -
if (sb.charAt(0)=='A') {
sb.setCharAt(0, 'B');
} else {
sb.setCharAt(0, 'C');
}
但是我在某处读到这也可以使用下面的代码来完成(并且它有效!)
sb.setCharAt(0, (char)(sb.charAt(0) + 1));
谁能解释一下上面的代码吗?
最佳答案
当您执行 char + int
时,char
会被解释为 int
,它表示 Unicode 表中所用字符的索引。
因此,当您执行 sb.charAt(0) + 1
时,它与 'A' + 1
相同,并且计算结果为 65 + 1
code> 等于 66
(Unicode 表中的 character indexed with that value 为 B
)。
现在,由于 setCharAt
需要第二个参数 char
,因此您必须将 int
(cast) 转换为 char
会返回 'B'
,而 sb.setCharAt(0, ..)
只是在位置 0
处设置该字符> 在你的 StringBuffer 中。
关于java - 有人可以解释一下下面与java中StringBuffer相关的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973812/