Programming Tips - Java: Best way to insert a String into another String

Date: 2017sep28 Update: 2025sep29 Language: Java Q. Java: Best way to insert a String into another String A. Use StringBuilder.insert() as shown in this full example:
class Demo { // Insert before * in a string. static String insertBeforeStar(final String in, final String more) { StringBuilder sb = new StringBuilder(in); int i = in.indexOf('*'); if (i < 0) return in; sb.insert(i, more); return sb.toString(); } public static final void main(String []args) { String out = insertBeforeStar("one * three", "two"); System.out.println("out=" + out); } }
Output:
out=one two* three
Of course, this isn't best in every case. But it's less error prone than using multiple substring()s.