[英]String replace in Java
我目前有一個包含字符A,B和C的字符串,例如字符串
"A some other random stuff B C"
其他隨機的東西不包含A,B或CI想分別用'A','B'和'C'替換A,B和C,目前我正在做的最好的方法是:
String.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'")
如果A,B和C是那些確切的單個字符,則cletus的答案可以正常工作,但如果它們可以是更長的字符串則不然,例如,你只是將它們稱為A,B和C. 如果它們是更長的字符串,您需要做:
String input = "FOO some other random stuff BAR BAZ";
String output = input.replaceAll("FOO|BAR|BAZ", "'$0'");
您還需要轉義FOO,BAR和BAZ中的任何特殊字符,以便它們不會被解釋為特殊的正則表達式符號。
使用正則表達式:
String input = "A some other random stuff B C";
String output = input.replaceAll("[ABC]", "'$0'");
輸出:
'A' some other random stuff 'B' 'C'
看看Apache Commons Lang的StringUtils
及其各種replace
方法。
我認為正則表達式並不適合,如果它們是相當復雜的字符串。
考慮將它包裝在您自己的實用程序方法中,將數組或列表作為參數。
public static String replace(String string, String[] toFind, String[] toReplace) {
if (toFind.length != toReplace.length) {
throw new IllegalArgumentException("Arrays must be of the same length.");
}
for (int i = 0; i < toFind.length; i++) {
string = string.replace(toFind[i], toReplace[i]);
}
return string;
}
也許Apache Commons或Google Code中已有一個。 如果您更喜歡第三方API以上的本土產品,請看一下。
編輯 :為什么downvoting技術上正確,但在您看來不是首選答案? 只是不要upvote。
其他人的答案更好,但在您嘗試學習的假設下,我想指出原始代碼的問題。
這將是你要做的事情的“固定”版本(使用你的風格,這很接近)以及你需要做的事情來使它工作:
public String quoteLetters(String s)
{
return s.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'");
}
以下是您遇到的問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.