gpt4 book ai didi

java - 替换字符串中第 i 次出现的最快方法

转载 作者:行者123 更新时间:2023-12-01 10:03:15 25 4
gpt4 key购买 nike

我有一个由 n 个相等的子字符串组成的字符串。例如,字符串 "hellooo dddd" 有 3 个 "dd" 子字符串(我说它出现了 3 次)。在更一般的情况下,字符串中有 n 个相等的子字符串,如何替换字符串中第 i 个出现的子字符串。类似 replace() 的方法用于第 i 个子字符串。我想在我的 android 代码中实现它。 (英语不是我的母语,所以请原谅任何错误。)。

最佳答案

public static String replace(String input, String pattern, int occurence, String replacement){
String result = input;
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(result);
if(occurence == 0){
return result;
} else if(occurence == 1){
m.find();
result = result.substring(0,m.start()) + replacement + result.substring(m.end());
} else {
m.find();
int counter = 1;
try {
while((counter<occurence)&&m.find(m.start()+1)){
counter++;
}
result = result.substring(0,m.start()) + replacement + result.substring(m.end());
} catch(IllegalStateException ise){
throw new IllegalArgumentException("There are not this many occurences of the pattern in the String.");
}
}
return result;
}

如果我理解正确的话,似乎做的事情与你想要的类似。

使用匹配器/模式系统,它可以支持更复杂的正则表达式。

关于java - 替换字符串中第 i 次出现的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36652203/

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