Browse - Programming Tips - What's the best way to insert a String into a String with Java?

Date: 2017sep28
Language: Java

Q.  What's the best way to insert a String into a String with Java?

A.  Use StringBuilder.insert()

// Insert before * in a string. String insertDemo(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(); }
Of course, this isn't best in every case. But less error prone than using multiple substring's.