簡體   English   中英

在StringBuilder字符串中替換“ char”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM