I need to replace a dynamic substring withing a larger string, but only once (i.e. first match). The String class provides only replace()
, which replaces ALL instances of the substring; there is a replaceFirst()
method but it only takes regexp instead of a regular string. I have two concerns with using regex:
1) my substring is dynamic, so might contain weird characters that mean something else in regex, and I don't want deal with character escaping.
2) this replacement happens very often, and I'm not sure whether using regex will impact performance. I can't compile the regex beforehand since the regex itself is dynamic!
I must be missing something here since this seems to me is a very basic thing... Is there a replaceFirst method taking regular string somewhere else in the java franework?
To replace the first occurrence of a character in Java, use the replaceFirst() method.
Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
You should use already tested and well documented libraries in favor of writing your own code!
StringUtils.replaceOnce("aba", "a", "") = "ba"
The StringUtils
class is from Apache Commons Lang3 package and can be imported in Maven like this:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With