上题回顾与解析
package test.question;
public class Question14 {
public static void main(String[] args){
System.out.println(
Question14.class.getName().replaceAll(".","/") + ".class");
}
你可能会认为程序会打印test.question.Question14 .class,但实际结果是
////////////////////////.class
解析: 问题在于String.replaceAll接受一个正则表达式作为它的第一个参数,而并非接受字符串。正则表达式"."可以匹配任何单个的字符,因此类中每一个字符都被替换成了斜杠"/"。
以下两种方法可修正结果: 1.java.util.regex.Pattern.quote方法,它接受一个字符串作为参数,返回一个正则表达式,这个正则表达式可以精确的匹配输入的字符串
public static void main(String[] args){
System.out.println(
Question14.class.getName().replaceAll(Pattern.quote("."),"/") + ".class");
}
2.org.apache.commons.lang.StringUtils.replcae方法
public static void main(String[] args){
System.out.println(
StringUtils.replace(Question14.class.getName(),".","/") + ".class");
}
每日一题
思考:下面的程序将会做什么?
public class Question15 {
public static void main(String[] args){
System.out.println("hello");
http://hello.com;
System.out.println("world");
}
}