Last active
August 29, 2015 14:22
-
-
Save jamiecurran/f364911b887d9b7aac49 to your computer and use it in GitHub Desktop.
string replace algorithm
This file contains hidden or 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
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