繁体   English   中英

如何替换Java中第一次出现的字符串

[英]How to replace first occurrence of string in Java

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

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

**如果测试包含如下输入,则不应替换

  1. 见评论,(末尾有空格)
  2. 看评论,
  3. 看评论**

我想得到如下输出,

Output: this is for some test, help us

您应该使用已经过测试且文档齐全的库来编写自己的代码。

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

Javadoc

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

马文

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

学分

我的回答是对以下内容的扩充: https : //stackoverflow.com/a/10861856/714112

您可以使用以下语句将第一次出现的文字字符串替换为另一个文字字符串:

String result = input.replaceFirst(Pattern.quote(search), Matcher.quoteReplacement(replace));

但是,这在后台做了很多工作,而用专门的函数来替换文字字符串则不需要这些工作。

使用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);

输出:

这是为了一些测试,帮助我们

您可以使用以下方法。

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;

}

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

使用 String 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);

你也可以在node.js中使用这个方法;

public static String replaceFirstOccurance(String str, String chr, String replacement){
    String[] temp = str.split(chr, 2);
    return temp[0] + replacement + temp[1];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM