那么,Java 1.3 没有 String.replaceAll 吗?我们可以自己写吗?
public class StringReplaceAll {
public static String replaceAll(String text, String find, String replace) {
if (text == null || find == null || replace == null) {
throw new NullPointerException();
}
if (find.length() == 0) {
throw new IllegalArgumentException();
}
int start = 0;
int end = text.indexOf(find, start);
if (end == -1) {
return text;
}
int findLen = find.length();
StringBuffer sb = new StringBuffer(text.length());
while (end != -1) {
sb.append(text.substring(start, end));
sb.append(replace);
start = end + findLen;
end = text.indexOf(find, start);
}
sb.append(text.substring(start));
return sb.toString();
}
public static void assertEquals(String s1, String s2) {
if (s1 == null || s2 == null)
throw new RuntimeException();
if (!s1.equals(s2))
throw new RuntimeException("<" + s1 + ">!=<" + s2 + ">");
}
public static void main(String[] args) {
assertEquals("lazy fox jumps lazy dog",
replaceAll("quick fox jumps quick dog",
"quick",
"lazy"));
assertEquals("quick fax jumps quick dag",
replaceAll("quick fox jumps quick dog", "o", "a"));
assertEquals("",
replaceAll("quick fox jumps quick dog",
"quick fox jumps quick dog",
""));
assertEquals("quick fox jumps quick dog",
replaceAll("quick fox jumps quick dog", "zzz", "xxx"));
assertEquals("quick fox jumps quick cat",
replaceAll("quick fox jumps quick dog", "dog", "cat"));
assertEquals("zzzzzzzzzzzzzzzzzzzzzzzzz",
replaceAll("aaaaaaaaaaaaaaaaaaaaaaaaa", "a", "z"));
assertEquals("zzzz", replaceAll("aa", "a", "zz"));
assertEquals("", replaceAll("", "a", "z"));
try {
replaceAll(null, "a", "z");
throw new RuntimeException();
} catch (NullPointerException e) {
}
try {
replaceAll("a", "z", null);
throw new RuntimeException();
} catch (NullPointerException e) {
}
try {
replaceAll("a", null, "z");
throw new RuntimeException();
} catch (NullPointerException e) {
}
try {
replaceAll("a", "", "z");
throw new RuntimeException();
} catch (IllegalArgumentException e) {
}
}
}