Skip to content

Instantly share code, notes, and snippets.

@xzzz9097
Last active August 29, 2015 14:06
Show Gist options
  • Save xzzz9097/c844f85aa72de080cc72 to your computer and use it in GitHub Desktop.
Save xzzz9097/c844f85aa72de080cc72 to your computer and use it in GitHub Desktop.
Java - Insert a string into another string
/**
* Function that inserts a specified string into another string. It uses java's StringBuilder.
* Usage: insertStringInString("dogs cats", "and", 4) -> "dogs and cats"
* @param string - The main string that should contain the new piece
* @param insertion - The piece to add
* @param position - The position from which to add the piece
* @return - The final string
*/
public static String insertStringInString(String string, String insertion, int position) {
// Only insert if the position is > -1 (useful with string.indexOf which returns -1
if (position > -1) {
// Create the string builder and append the insertion at the specified position
StringBuilder mStringBuilder = new StringBuilder(string);
mStringBuilder.insert(position, insertion);
// Return the final string
return mStringBuilder.toString();
} else {
// Return the original string
return string;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment