替换StringBuilder字符串中的“字符”

NoobEditor

我的要求很简单,获取一个char位置并将其替换为另一个。
唯一要注意的是,char和及其index在运行时出现,并且不能进行硬编码。

我实际实现的虚拟代码:

public static void main(String args[])
{
   StringBuilder sb = new StringBuilder("just going nuts")  ;
   System.out.println(" "+sb);
   //System.out.println(sb.charAt(4)); //this works
   sb.setCharAt(sb.indexOf((sb.charAt(4))), sb.charAt(0)); //line 8 -error line
   System.out.println(" "+sb);
}

我什至尝试char用引号括起来:

sb.setCharAt(sb.indexOf(( "\""+sb.charAt(4)+"\"" )), sb.charAt(0));

但仍然是相同的错误

错误

line no:8: cannot find symbol
symbol : method indexOf(char)
location: class java.lang.StringBuilder
sb.setCharAt(sb.indexOf((sb.charAt(4))), sb.charAt(0));

我不太熟练使用Java,但是找不到setCharAt像这种情况下具有动态值的函数示例!

Dimitrisli

错误是因为indexOf期望String不是,char所以您要做的就是将其包装String.valueOf

sb.setCharAt(sb.indexOf(String.valueOf((sb.charAt(4)))), sb.charAt(0));

输出

 just going nuts
 justjgoing nuts

当您键入甚至提供解决方案时(在IntelliJ以下),现代IDE应该会捕获此编译时错误:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章