Skip to content

Instantly share code, notes, and snippets.

@VapidLinus
Created May 23, 2014 18:37
Show Gist options
  • Save VapidLinus/d64f166d0031424c7f42 to your computer and use it in GitHub Desktop.
Save VapidLinus/d64f166d0031424c7f42 to your computer and use it in GitHub Desktop.
package net.uniqraft.api;
public final class StringTools {
public static String replaceAll(String text, String replace, String replacement) {
if (replace == replacement)
return text;
String currentText = null;
String newText = text;
do {
currentText = newText;
newText = replaceFirst(newText, replace, replacement);
} while (currentText != newText);
return newText;
}
public static String replaceFirst(String text, String replace, String replacement) {
int found = 0;
int foundAt = -1;
// Loop through each char
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
// Does char match replace char?
if (replace.charAt(found) == c) {
// We found another match
found++;
// Have we found the entire replace text?
if (found == replace.length()) {
// Mark location we found match first at
foundAt = i - found + 1;
break;
}
}
}
// Did we get a match?
if (foundAt != -1) {
// Replace text
return text.substring(0, foundAt) + replacement + text.substring(foundAt + replace.length(), text.length());
}
return text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment