那麼,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) {
}
}
}
這可能是環境比Java 1.4,當[java.util.regex中]年長(http://docs.oracle.com/javase/6/docs/api/java/util/regex /package-summary.html)首次引入。 – nhahtdh 2013-04-25 11:02:32
是的。它肯定比那個更早 – 2013-04-25 11:03:50
當然,你也應該使用高效的JVM來進行開發,因爲你會遇到很多次這些東西。 1.4中添加了許多API ... – 2013-04-25 11:05:28