【发布时间】: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 创建一个新字符串
-
并且在发布问题之前表现出一些努力