How to replace first occurrence of string in Java
You can use replaceFirst(String regex, String replacement)
method of String.
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