java - 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 的那个实例。我见过人们只替换子字符串的第一个实例,而不是之后的实例。我该怎么做?
解决方案
我会使用类中的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;
推荐阅读
- php - 将单选按钮值和带有单选按钮的文本发送到 php
- javascript - react-multiselect-checkboxes 自定义 DropdownButton
- javascript - 有没有办法从字符串中读取 html 标题
- python - SQLAlchemy:具有自定义集合的映射器,用于不知道更改的双链表
- shell - 从 shell 脚本上传 Github 工件
- reactjs - 如何使用firebase firestore“哪里!=”
- jenkins - 检查来自多个 GitHub 存储库的拉取请求的 Jenkins 项目
- .net - 我可以在 Xamarin.Forms 中使用 WebView2 吗?我需要在 Android、iOS 和 Windows (UWP) 中使用它,而不是原来的 WebView
- angular - 如何使用 Angular 从 Graph Api 获取 Facebook 额外用户数据?
- r - Dplyr 语法选择列并将它们转换为单个列表