How to Replace Substring from String in Java


How can we replace a substring from a string in Java?

Suppose we want to replace {dir} with the word path.

String template = "/random/{dir}"

1. Using replace() or replaceAll()

It’s quite simple using replace() and replaceAll(), both of which accept regular expressions.

String replaced = template.replace("{dir}", "path");
String replaced = template.replaceAll("{dir}", "path");

2. Using StringBuffer

If we know the start and end index of the substring to replace, we can use StringBuffer,

StringBuffer templateBuf = new StringBuffer(template);
templateBuf.replace(startIndex, endIndex, "path");