我會寫的方法和使用String.indexOf()
和String.substring()
更換每個字符的第一次出現,像
public static String replaceFirst(String in, char a, char b) {
int pos1 = in.indexOf(a);
int pos2 = in.indexOf(b);
if (pos2 < pos1) {
int temp = pos2;
pos2 = pos1;
pos1 = temp;
}
StringBuilder sb = new StringBuilder();
if (pos1 != -1 && pos2 != -1 && pos1 != pos2) {
sb.append(in.substring(0, pos1));
sb.append(b);
sb.append(in.substring(pos1 + 1, pos2));
sb.append(a);
sb.append(in.substring(pos2 + 1));
} else {
sb.append(in);
}
return sb.toString();
}
然後你可以用東西把它像
public static void main(String[] args) {
String s = "tha";
System.out.println(replaceFirst(s, 'h', 'a'));
}
輸出是要求
tah
編輯
爲了支持您額外要求的功能,您還必須跟蹤開始位置。首先,我們可以委託我們以前的方法,新的方法,像這樣 -
public static String replaceFirst(String in, char a, char b) {
return replaceFirst(in, 0, a, b);
}
然後,我們只需調用indexOf(char, int)
指定最低的指數 -
public static String replaceFirst(String in, int start, char a, char b) {
int pos1 = in.indexOf(a, start);
int pos2 = in.indexOf(b, start);
StringBuilder sb = new StringBuilder();
if (pos1 != -1 && pos2 != -1 && pos1 != pos2) {
if (pos2 < pos1) {
int temp = pos2;
pos2 = pos1;
pos1 = temp;
}
sb.append(in.substring(0, pos1));
sb.append(b);
sb.append(in.substring(pos1 + 1, pos2));
sb.append(a);
sb.append(in.substring(pos2 + 1));
} else {
sb.append(in);
}
return sb.toString();
}
最後,我們可以用
叫它
public static void main(String[] args) {
String s = "afab";
s = replaceFirst(s, 'a', 'f');
s = replaceFirst(s, 2, 'a', 'b');
System.out.println(s);
}
,輸出
faba
正則表達式是答案嗎?你的其他投入是什麼? – 2014-09-29 00:37:28
使用臨時佔位符值。 – 2014-09-29 00:38:56
如果你想要一個通用的解決方案,你需要提供更多的示例輸入。 – qbit 2014-09-29 00:47:14