Jag*_*esh 39 java string replace
我想在下面替换第一次出现的String.
String test = "see Comments, this is for some test, help us"
Run Code Online (Sandbox Code Playgroud)
**如果测试包含如下输入,则不应替换
我想得到如下输出,
Output: this is for some test, help us
Run Code Online (Sandbox Code Playgroud)
提前致谢,
Asi*_*sif 79
您可以使用replaceFirst(String regex, String replacement)String的方法.
Sri*_*bat 17
您应该使用已经过测试并且文档齐全的库来支持编写自己的代码.
org.apache.commons.lang3.
StringUtils.replaceOnce("coast-to-coast", "coast", "") = "-to-coast"
Run Code Online (Sandbox Code Playgroud)
甚至还有一个不区分大小写的版本(这很好).
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我的答案是增加:https://stackoverflow.com/a/10861856/714112
Eng*_*uad 14
String test = "see Comments, this is for some test, help us";
String newString = test.substring(test.indexOf(",") + 2);
System.out.println(newString);
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
这是一些测试,帮助我们
Har*_*hna 12
您可以使用以下语句替换第一次出现的字符串.
String result = input.replaceFirst(Pattern.quote(stringToReplace), stringToReplaceWith);
Run Code Online (Sandbox Code Playgroud)
此链接包含完整的程序,包括测试用例.