java中string的replace方法解析
今天在写代码时犯了一个挺低级的错误,所以记录在此,以免以后再犯。
代码其实很简单,就是用string的replace方法,如下:
public void doFilter() {// TODO Auto-generated method stub String mes = "This is a < script >"; mes.replace('<', '[').replace('>', ']'); //mes += "---HtmlFilter----"; System.out.println(mes); }但打印输入的一直是This is a < script >,开始还以为是replace方法没有起作用。在看了replace方法的源码以后才恍然大悟,源码如下:
public String replace(char oldChar, char newChar) {if (oldChar != newChar) { int len = count; int i = -1; char[] val = value; /* avoid getfield opcode */ int off = offset; /* avoid getfield opcode */ while (++i < len) {if (val[off + i] == oldChar) { break;} } if (i < len) {char buf[] = new char[len];for (int j = 0 ; j < i ; j++) { buf[j] = val[off+j];}while (i < len) { char c = val[off + i]; buf[i] = (c == oldChar) ? newChar : c; i++;}return new String(0, len, buf); }}return this; }从源码我们可以看到,replace方法中,如果替换字符后,它是返回一个重新new的string对象,原来的字符串是没有变的。所以用replace方法时一定要有一个string的变量接受替换的结果。所以最初的方法应该做如下改动:
public void doFilter() {// TODO Auto-generated method stub String mes = "This is a < script >"; String temp = mes.replace('<', '[').replace('>', ']'); //mes += "---HtmlFilter----"; System.out.println(temp ); }这样输出如愿的字符串了。