How to replace string only once without regex in Java?
java, string
Solution
Use `bigString.indexof(smallString)` to get the index of the first occurrence of the small string in the big one (or -1 if none, in which case you're done). Then, use `bigString.substring` to get the pieces of the big string before and after the match, and finally `concat` to put those before and after pieces back together, with your intended replacement in the middle.
Problem
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?