本文介紹了Java替換字符串特定位置的字符?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試替換字符串特定位置的字符.
I am trying to replace a character at a specific position of a string.
例如:
String str = "hi";
將字符串位置 #2 (i) 替換為另一個字母k"
replace string position #2 (i) to another letter "k"
我該怎么做?謝謝!
推薦答案
Petar Ivanov 對 替換字符串問題中特定索引處的字符
字符串在 Java 中是不可變的.您無法更改它們.
String are immutable in Java. You can't change them.
您需要創建一個替換字符的新字符串.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
或者您可以使用 StringBuilder:
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
這篇關于Java替換字符串特定位置的字符?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!