Dave's Brain

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.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.