假设我有一个字符串,我想将该字符串中的第二个“a”更改为“e”。
String elephant = "elaphant";
我尝试使用String.replace(),但是它替换了字符串中的所有a,返回“elephent”。
elephant.replace("a", "e");
我可以使用任何循环或方法来完成此任务吗?谢谢大家。
答案 0 :(得分:2)
您可以将其转换为char数组,切换出所需的字母,然后将其转换回String?
String elephant = "elaphant";
int index = -1;
int count = 0;
while(count < 2) {
index = elephant.indexOf("a", index+1);
count++;
}
if(index >= 0 && index < elephant.length()) {
char[] tmp = elephant.toCharArray();
tmp[index] = "e";
elephant = new String(tmp);
}
或者如果您更喜欢StringBuilder
StringBuilder sbTemp = new StringBuilder(elephant);
sbTmp = sbTmp.replace(index, index+1, "e");
elephant = sbTmp.toString();
答案 1 :(得分:1)
您需要获取第一个字母的索引。
尝试使用indexOf方法。
int myIndex = elephant.indexOf('a');
获得索引后,使用StringBuilder替换该值。类似的东西:
StringBuilder sb = new StringBuilder(elephant);
sb[index] = myIndex;
elephant = sb.ToString();
答案 2 :(得分:0)
代码:
String elephant = "elaphant";
//convert the string to array of string
String[] sp = elephant.split("");
int countA = 0;
boolean seenTwice = false;
String result = "";
for (int i = 0; i < sp.length; i++) {
//count number of times that a has been seen
if (sp[i].equals("a")) {
countA++;
}
// if a has been seen twice and flag seenTwice has not been see
if (countA == 2 && !seenTwice) {
result += "e";
seenTwice = true;
} else {
result += sp[i];
}
}
System.out.println(result);
输出:
elaphent