我正在处理一个作业,该作业要求您编写一种方法来用新的子字符串替换子字符串,但是仅当原始子字符串在其字符串中重复给定次数且仅在该时间替换子字符串时重复。 我们得到:
public class Statement
{
private String remark;
public Statement (String a){
remark = a;
}
/**Returns the index in the statement of the kth str;
*returns -1 if kth time does not exist.
*Precondition: str.length() > 0 and k > 0
*Postcondition: the current statement is not modified.
*/
public int locateKth (String str, int k)
{ /*implementation not shown*/ }
/**Modifies the current statement by replacing the kth time of str with newStr.
*If the kth time does not exist, the current statement is unchanged.
*Precondition: str.length() > 0 and k > 0
*/
public void changeKth (int k, String str, String newStr)
然后要求我们编写方法changeKth,并给出其工作方式示例:
Statement ex1 = new Statement(“The cat in the hat knows a lot about
that.”)
ex1.changeKth(1, “at”, “ow”);
System.out.println(ex1);
返回:戴着帽子的牛对此非常了解。
我知道我将必须索引str的k个实例,但是我不确定从那里去哪里只能替换str的那个实例。我见过人们仅替换子字符串的第一个实例,但绝不替换之后的实例。我该怎么办?
答案 0 :(得分:0)
我将使用indexOf(String str, int fromIndex)
类中的String
方法来查找str
在句子中出现的所有时间;将fromIndex
设置为上一次出现的str
的索引,直到遍历整个句子为止。如:
String sentence;
String str;
String newStr;
int k;
List<Integer> indexes = new ArrayList<Integer>();
int lastIndex = 0;
//LOOP UNTIL WE'VE GONE THROUGH THE WHOLE SENTENCE
while(lastIndex < sentence.length){
//GET THE FIRST PLACE WHERE str APPEARS AFTER THE LAST INDEX WE'VE ALREADY LOOKED AT
int index = sentence.indexOf(str, lastIndex);
//KEEP TRACK OF THE INDEXES str APPEARS AT IN THE SENTENCE
indexes.add(index);
//UPDATE THE LAST INDEX WE'VE LOOKED AT
lastIndex = index;
}
//GET KTH INDEX
int kthIndex = indexes.get(k);
//GET THE SENTENCE BEFORE str APPEARS AT THE kthIndex
String result = sentence.substring(0, kthIndex)
//ADD newStr (REPLACE str WITH newStr)
result += newStr;
//ADD THE LAST PART OF THE SENTENCE AFTER str APPEARS AT THE kthIndex
result += sentence.substring(kthIndex + str.length, sentence.length);
//THIS IS THE RESULT
return result;