public class Comments { StringBuilder template; final String holder1 = "←"; final String holder2 = "↓"; final String holder3 = "↖"; int quote = 1024; public Comments(String template) throws Exception { this.template = new StringBuilder(template); //这段代码可有可无,安全起见最好加上 if (template.indexOf(holder1) > -1) throw new Exception("this file already have the placeholder1, please check your file before compile!!"); if (template.indexOf(holder2) > -1) throw new Exception("this file already have the placeholder2, please check your file before compile!!"); if (template.indexOf(holder3) > -1) throw new Exception("this file already have the placeholder3, please check your file before compile!!"); //这段代码可有可无,安全起见最好加上 } public StringBuilder analysis() { String[] str1 = new String[quote]; escape(template,"\\",holder1,str1); //---------------------------------------------------------------------------- String[] str2 = new String[quote]; replace(template,"\"",holder2,str2); //---------------------------------------------------------------------------- String[] str3 = new String[quote]; replace(template,"\"",holder3,str3); //---------------------------------------------------------------------------- replaceA(template,"//","\n"); replaceB(template,"/*","*/"); //---------------------------------------------------------------------------- restore(template,str3,holder3); restore(template,str2,holder2); restore(template,str1,holder1); return template; } private void restore(StringBuilder sb,String[] from,String holder){ for (int i = 0; i < from.length; i++) { String ch = holder+i; int po = sb.indexOf(ch); if(po > -1) sb.replace(po,po+ch.length(),from[i]); } } private void escape(StringBuilder sb,String ch,String holder,String[] restore){ int po1 = sb.indexOf(ch); int po2 = po1+2; int index = 0; while(po1 != -1){ restore[index] = sb.substring(po1, po2); sb.replace(po1,po2,holder+index); index++; po1 = sb.indexOf(ch); po2 = po1+2; } } private void replace(StringBuilder sb,String ch,String holder,String[] restore){ int po1 = sb.indexOf(ch); int po2 = sb.indexOf(ch,po1+1)+1; int index = 0; while(po1 != -1 && po2 != -1){ restore[index] = sb.substring(po1, po2); sb.replace(po1,po2,holder+index); index++; po1 = sb.indexOf(ch); po2 = sb.indexOf(ch,po1+1)+1; } } private void replaceA(StringBuilder sb,String from,String to){ int po1 = sb.indexOf(from); int po2 = sb.indexOf(to,po1+1); while(po1 != -1 && po2 != -1){ sb.replace(po1,po2,""); po1 = sb.indexOf(from); po2 = sb.indexOf(to,po1+1); } } private void replaceB(StringBuilder sb,String from,String to){ int po1 = sb.indexOf(from); int po2 = sb.indexOf(to,po1+1)+2; while(po1 != -1 && po2 != -1){ sb.replace(po1,po2,""); po1 = sb.indexOf(from); po2 = sb.indexOf(to,po1+1)+2; } } }
标签:Java,String,indexOf,po2,po1,注释,template,移除,sb From: https://www.cnblogs.com/laremehpe/p/16639410.html