有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想替换以下字符串中第一个出现的字符串

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

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

  1. 请参见注释(末尾有空格)
  2. 见评论
  3. 见评论**

我想得到如下输出:

 Output: this is for some test, help us

提前感谢,


共 (6) 个答案

  1. # 1 楼答案

    使用^{}

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

    输出:

    this is for some test, help us

  2. # 2 楼答案

    你也可以使用这种方法

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

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

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

    然而,这在后台做了很多工作,而替换文字字符串的专用函数不需要这些工作

  4. # 4 楼答案

    为了编写自己的代码,您应该使用已经测试过且有良好文档记录的库

    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

  5. # 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;
    
    }
    

    下面的link提供了使用正则表达式和不使用正则表达式替换第一个出现的字符串的示例

  6. # 6 楼答案

    可以使用字符串的^{}方法