gpt4 book ai didi

java - 匹配子字符串后替换字符串的所有后续字符

转载 作者:行者123 更新时间:2023-12-02 12:41:11 25 4
gpt4 key购买 nike

我尝试用另一个字符替换字符串中的一个字符及其后面的所有字符。

这是我到目前为止的代码。

String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)

结果应该是:“Petabc”

我非常感谢任何有关此事的帮助!

最佳答案

实现目标的方法:

  • 在字符串中搜索要替换的序列的第一次出现
  • 使用该索引并使用 String#substring 剪切字符串
  • 将替换序列添加到刚刚创建的子字符串的末尾

鳍。

祝你好运。

编辑

在代码中它可能看起来像这样(未经测试)

public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);

if(index >= 0)
{
return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
return null; //String 'input' doesn't contain String 'replace'
}

关于java - 匹配子字符串后替换字符串的所有后续字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44927855/

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