【问题标题】:Java Replace a substring after a certain number of repeats of that substringJava 在子字符串重复一定次数后替换子字符串
【发布时间】:2018-10-18 00:58:48
【问题描述】:

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

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

【问题讨论】:

  • 使用 for 循环,而不是使用 String.replace,而是使用 substring 和 indexof 创建一个新字符串
  • 并且在发布问题之前表现出一些努力

标签: java substring


【解决方案1】:

我会使用String 类中的indexOf(String str, int fromIndex) 方法来查找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;

【讨论】:

    猜你喜欢
    • 2014-11-05
    • 2022-01-07
    • 2019-08-19
    • 2014-03-21
    • 2013-05-18
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    相关资源
    最近更新 更多