How to replace first occurrence of string in Java

后端 未结 6 996
悲&欢浪女
悲&欢浪女 2020-11-29 07:20

I want to replace first occurrence of String in the following.

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

**If test c

相关标签:
6条回答
  • 2020-11-29 07:32

    Use String replaceFirst to swap the first instance of the delimiter to something unique:

    String input = "this=that=theother"
    String[] arr = input.replaceFirst("=", "==").split('==',-1);
    String key = arr[0];
    String value = arr[1];
    System.out.println(key + " = " + value);
    
    0 讨论(0)
  • 2020-11-29 07:41

    You can use replaceFirst(String regex, String replacement) method of String.

    0 讨论(0)
  • 2020-11-29 07:41

    You can use following statement to replace first occurrence of literal string with another literal string:

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

    However, this does a lot of work in the background which would not be needed with a dedicated function for replacing literal strings.

    0 讨论(0)
  • 2020-11-29 07:45

    You can use following method.

    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;
    
    }
    

    Following link provide examples for replacing first occurrence of string using with and without regular expressions.

    0 讨论(0)
  • 2020-11-29 07:54

    You should use already tested and well documented libraries in favor of writing your own code.

    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-

    There's even a version that is case insensitive (which is good).

    Maven

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

    Credits

    My answer is an augmentation of: https://stackoverflow.com/a/10861856/714112

    0 讨论(0)
  • 2020-11-29 07:54

    Use 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:

    this is for some test, help us

    0 讨论(0)
提交回复
热议问题