I was translating a DotNet project to Java. In code, CSharp insert String function was used and I wrote my own Java function to insert characters/string at a specific index of string. Following is the code
public static String insert(String originalString,int offset, String injectString) {
if(offset>= originalString.length()) {
return originalString;
}
String firstPart = originalString.substring( 0, offset);
String secondPart = originalString.substring( offset);
return firstPart.concat( injectString ).concat( secondPart );
}
Later on, I found the StringBuffer's built-in insert function for the same purpose
StringBuffer buffer = new StringBuffer();
buffer.append( "Hello Java" );
buffer.insert( 6, "to " );
System.out.println( buffer ); // OUTPUT Hello to Java
Comments
Post a Comment