Skip to content

Instantly share code, notes, and snippets.

@jamiecurran
Last active August 29, 2015 14:22
Show Gist options
  • Save jamiecurran/f364911b887d9b7aac49 to your computer and use it in GitHub Desktop.
Save jamiecurran/f364911b887d9b7aac49 to your computer and use it in GitHub Desktop.
string replace algorithm
public String replace(String original, String toReplace, String replaceWith) {
char[] origArray = original.toCharArray();
char[] toReplaceArray = toReplace.toCharArray();
StringBuilder result = new StringBuilder();
int index = 0;
while(index < origArray.length){
if(isPotentialMatch(origArray[index], toReplaceArray[index])){
if(isMatch(index, origArray, toReplaceArray)){
result.append(replaceWith);
index += toReplace.length() - 1;
}
} else {
result.append(origArray[index]);
}
index++;
}
return result.toString();
}
private boolean isPotentialMatch(char a, char b) {
return a == b;
}
private boolean isMatch(Integer index, char[] original, char[] toReplace) {
for(int i = index; i < toReplace.length; i++){
if(original[i] != toReplace[i]){
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment