请看以前的html编码函数:
public class HtmlEncode{ String re; public String replace(String con,String tag,String rep){ int j=0; int i=0; int k=0; String RETU=""; String temp=con; int tagc=tag.length(); while(i< con.length()){ if(con.substring(i).startsWith(tag)){ temp=con.substring(j,i)+rep; RETU+=temp; i+=tagc; j=i; }else{ i+=1; } } RETU+=con.substring(j); return RETU; }
public String htmlEncode(String s){
re=replace(s,"<","<");
re=replace(re,">",">");
re=replace(re,"\n","
");
re=replace(re," "," ");
re=replace(re,"'","'");
return re;
}
//下面是使用的例子:
public static void main(String[] args){
String s="<body>'home' cwb</body>";
HtmlEncode he=new HtmlEncode();
System.out.println(he.htmlEncode(s));
}
}
在jdk1.4以后,由于引进了正则表达式,在String类中新增了
public String replaceAll(String regex, String replacement)方法。
像上面的问题就非常容易:
public class Test{
public static void main(String[] args){
String s="<body>'home' cwb</body>";
System.out.println(s.replaceAll("<","<"));
}
}