化学式网页展示的格式化

来源:互联网 发布:男士补水面膜 知乎 编辑:程序博客网 时间:2024/04/28 04:26

简单的先讲下处理思路:

化学式标准为字母和数字组成,如果为离子式,则会在末尾有“+”或者“-”用来标识所携带的电荷数。一般情况下,化学式以字母开头,以数字或电荷标识结尾,如果在化学方程式中,也会以数字开头。因此处理逻辑为逐个检测化学式的字符,根据该字符是字母还是数字进行处理,如果为字母,则正常进行显示,如果为数字,则进行以下情况进行区分:
1.如果在首位,则该数字正常显示;
2.如果该数字存在后一位字符,且为电荷标识,则根据电荷数的位数,截取对应的长度展示为上标;
3.普通情况,数字展示为下标

在开发中,使用一个临时字符串来记录各段格式化后的小字符串,相关代码如下:

private static final String subStart = "<sub>";private static final String subEnd = "</sub>";private static final String supStart = "<sup>";private static final String supEnd = "</sup>";/** *  * @param source 未格式化的化学式 * @param elecNum 电荷数(正整数) * @return */public static String convert(String source,int elecNum){StringBuffer formatted = new StringBuffer();StringBuffer original = new StringBuffer(source);StringBuffer temp = new StringBuffer();for(int i=0;i<original.length();i++){if(i==0){formatted.append(original.substring(i, i+1));continue;}char ch = original.charAt(i);if(Character.isDigit(ch)){temp.append(ch);if(i==original.length()-1){formatted.append(subStart).append(temp).append(subEnd);}}else{if(ch=='+'||ch=='-'){temp.append(ch);String elecStr = "";if(elecNum>0){elecStr = Integer.toString(elecNum);}int elecLengthWithSymbol = elecStr.length()+1;if(temp.length()>elecLengthWithSymbol){//如果为SO4 2-这种离子式,进入该分支formatted.append(subStart).append(temp.substring(0, temp.length()-elecLengthWithSymbol)).append(subEnd);formatted.append(supStart).append(temp.substring(temp.length()-elecLengthWithSymbol, temp.length())).append(supEnd);}else{//如果为H+这种离子式,进入该分支formatted.append(supStart).append(temp).append(supEnd);}}else{if(temp.length()>0){formatted.append(subStart).append(temp).append(subEnd);}formatted.append(ch);}if(temp.length()>0){temp.delete(0, temp.length());}}}return formatted.toString();}
运行结果如下图:

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8");PrintWriter out = resp.getWriter(); String res1 = ChemicalFormulaFormat.convert("Si",0);String res2 = ChemicalFormulaFormat.convert("O22-",2);String res3 = ChemicalFormulaFormat.convert("3SO42-",2);String res4 = ChemicalFormulaFormat.convert("Cu2(OH)2CO3",0);String res5 = ChemicalFormulaFormat.convert("H+",1);String res6 = ChemicalFormulaFormat.convert("Cl-",1);String res7 = ChemicalFormulaFormat.convert("2Na2SO4",0);String res8 = ChemicalFormulaFormat.convert("Na2S2O3",0);out.println("<HTML>" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H5>" + res1 + "</H5>\n" + "<H5>" + res2 + "</H5>\n" + "<H5>" + res3 + "</H5>\n" + "<H5>" + res4 + "</H5>\n" + "<H5>" + res5 + "</H5>\n" + "<H5>" + res6 + "</H5>\n" + "<H5>" + res7 + "</H5>\n" + "<H5>" + res8 + "</H5>\n" + "</BODY></HTML>");}


0 0
原创粉丝点击