首页 > 解决方案 > Java 在子字符串重复一定次数后替换子字符串

问题描述

我正在做一个作业,要求您编写一个方法来用新的子字符串替换子字符串,但前提是原始子字符串在其字符串中重复给定次数,并且仅在该重复处替换子字符串。我们得到:

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 的那个实例。我见过人们只替换子字符串的第一个实例,而不是之后的实例。我该怎么做?

标签: javasubstring

解决方案


我会使用类中的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;

推荐阅读