我想替换所有'.'和' '一个'_'
但我不喜欢我的代码......
是否有更有效的方法来做到这一点:
String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".","_");
Run Code Online (Sandbox Code Playgroud)
?
toLowerCase()就在那里,因为我希望它也更低......
ben*_*y23 69
String new_s = s.toLowerCase().replaceAll("[ .]", "_");
Run Code Online (Sandbox Code Playgroud)
编辑:
replaceAll正在使用正则表达式,.在字符类中使用[ ]只识别一个.而不是任何字符.
使用String#replace()代替String#replaceAll(),您不需要正则表达式进行单字符替换。
我创建了以下类来测试什么更快,试一试:
public class NewClass {
static String s = "some_string with spaces _and underlines";
static int nbrTimes = 10000000;
public static void main(String... args) {
long start = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doOne();
System.out.println("using replaceAll() twice: " + (new Date().getTime() - start));
long start2 = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doTwo();
System.out.println("using replaceAll() once: " + (new Date().getTime() - start2));
long start3 = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doThree();
System.out.println("using replace() twice: " + (new Date().getTime() - start3));
}
static void doOne() {
String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".", "_");
}
static void doTwo() {
String new_s2 = s.toLowerCase().replaceAll("[ .]", "_");
}
static void doThree() {
String new_s3 = s.toLowerCase().replace(" ", "_").replace(".", "_");
}
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
使用 replaceAll() 两次:100274
使用 replaceAll() 一次:24814
使用 replace() 两次:31642
当然,我还没有分析应用程序的内存消耗,这可能会产生非常不同的结果。