[英]Replacing a “char” in StringBuilder string
我的要求非常簡單,獲取一個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
函數示例!
錯誤是因為indexOf
期望String
不是char
所以您要做的就是用String.valueOf
包裝它
sb.setCharAt(sb.indexOf(String.valueOf((sb.charAt(4)))), sb.charAt(0));
輸出
just going nuts
justjgoing nuts
當您鍵入甚至提供解決方案時,現代IDE應該會捕獲此編譯時錯誤(在IntelliJ以下的情況下):
嘗試添加空字符串
sb.setCharAt(sb.indexOf((sb.charAt(4))+""), sb.charAt(0));
由於sb.indexOf()使用字符串而不是字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.