如何取代Java字符串的第一次出现如何取代Java字符串的第一次出现(How to replace

2019-05-17 07:51发布

我想替换以下字符串的第一次出现。

  String test = "see Comments, this is for some test, help us"

**如果测试包含输入如下不应该取代

  1. 看评论,(与空间末)
  2. 看评论,
  3. 看评论**

我想要得到的输出如下,

 Output: this is for some test, help us

提前致谢,

Answer 1:

您可以使用replaceFirst(String regex, String replacement)字符串的方法。



Answer 2:

你应该有利于编写自己的代码的使用已经测试并有据可查的库。

org.apache.commons.lang3.
  StringUtils.replaceOnce("coast-to-coast", "coast", "") = "-to-coast"

的Javadoc

  • https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#replaceOnce-java.lang.String-java.lang.String-java.lang.String-

甚至还有一个版本是不区分大小写(这是很好)。

Maven的

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

积分

我的回答是的增强: https://stackoverflow.com/a/10861856/714112



Answer 3:

使用substring(int beginIndex)

String test = "see Comments, this is for some test, help us";
String newString = test.substring(test.indexOf(",") + 2);
System.out.println(newString);

OUTPUT:

这对于一些测试,帮助我们



Answer 4:

您可以使用下面的语句来替换字符串的第一次出现。

String result = input.replaceFirst(Pattern.quote(stringToReplace), stringToReplaceWith);

此链接有包括测试用例完整的程序。



Answer 5:

您可以使用下面的方法。

public static String replaceFirstOccurrenceOfString(String inputString, String stringToReplace,
        String stringToReplaceWith) {

    int length = stringToReplace.length();
    int inputLength = inputString.length();

    int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);

    String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
            + inputString.substring(startingIndexofTheStringToReplace + length, inputLength);

    return finalString;

}

下面的链接替换使用和不使用正则表达式使用字符串的第一次出现提供了范例。



Answer 6:

使用字符串replaceFirst的分隔符的第一个实例交换到一些独特的东西:

String input = "this=that=theother"
String[] arr = input.replaceFirst("=", "==").split('==',-1);
String key = arr[0];
String value = arr[1];
System.out.println(key + " = " + value);


文章来源: How to replace first occurrence of string in Java