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); } 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; }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 ); }