Last active
August 29, 2015 14:06
-
-
Save xzzz9097/c844f85aa72de080cc72 to your computer and use it in GitHub Desktop.
Java - Insert a string into another string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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