gpt4 book ai didi

java - 用包含原始子字符串的条件子字符串替换多次出现的子字符串

转载 作者:行者123 更新时间:2023-11-30 10:36:00 25 4
gpt4 key购买 nike

抱歉,标题太长了,但作为初学者,我在这里不知所措......可能我找不到现有的解决方案,因为我不知道要搜索的术语。

我想要做的是用包含原始子字符串的一些条件子字符串替换字符串中的所有子字符串。一个例子可能更清楚:

String answerIN = "Hello, it is me. It is me myself and I."
//should become something like:
String answerOUT = "Hello, it is <sync:0> me. It is <sync:1> me myself and I"

所以子字符串“me”应该被自己加上一些条件的东西替换。到目前为止我尝试的方法不起作用,因为我一直在替换替换的子字符串。所以我最终得到:

String answerOUT = "Hello, it is <sync:0> <sync:1> me. It is <sync:0> <sync:1> me myself and I"

我的代码:

        String answerIN = "Hello, it is me. It is me myself and I.";
String keyword = "me";
int nrKeywords = 2; //I count this in the program but that's not the issue here

if (nrKeywords != 0){
for (int i = 0; i < nrKeywords; i++){
action = " <sync" + i + "> " + keyword;
answerIN = answerIN.replace(keyword, action);
System.out.println("New answer: " + answerIN);
}
}

我不知道如何不替换已替换的字符串的子字符串部分。

最佳答案

String#replace 将始终用您要替换的内容替换您要查找的 String 的每次出现。所以这对于常规 String#replace 是不可能的,因为没有“只能从这里到那里替换”。

您可以使用 String 的子字符串方法来替换每个出现的地方:

String input = "Hello, it is me. It is me myself and I.";
String output = "";
String keyword = "me";
int nextIndex = input.indexOf(keyword), oldIndex = 0, counter = 0;

while(nextIndex != -1) {
output += input.substring(oldIndex, nextIndex-1) + " <sync:" + counter + "> ";
oldIndex = nextIndex;
nextIndex = input.indexOf(keyword, nextIndex+1);
++counter;
}
output += input.substring(oldIndex);
System.out.println(output);

O/P

Hello, it is <sync:0> me. It is <sync:1> me myself and I.

关于java - 用包含原始子字符串的条件子字符串替换多次出现的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40803382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com