How to replace first occurrence of string in Java

2020-01-26 08:25发布

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

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

**If test contains the input as follows it should not replace

  1. See Comments, (with space at the end)
  2. See comments,
  3. See Comments**

I want to get the output as follows,

 Output: this is for some test, help us

Thanks in advance,

6条回答
何必那么认真
2楼-- · 2020-01-26 08:48

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.

查看更多
Explosion°爆炸
3楼-- · 2020-01-26 08:51

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

查看更多
叛逆
4楼-- · 2020-01-26 08:56

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

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

查看更多
劫难
5楼-- · 2020-01-26 08:58

You can use following statement to replace first occurrence of string.

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

This link has complete program including test cases.

查看更多
Luminary・发光体
6楼-- · 2020-01-26 09:01
小情绪 Triste *
7楼-- · 2020-01-26 09:04

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);
查看更多
登录 后发表回答