import java.util.*;
public class SubAndSup
{
public static String setString(String s)
{
StringBuffer str=new StringBuffer(s);
StringBuffer strSup1=new StringBuffer("<sup>");
StringBuffer strSup2=new StringBuffer("</sup>");
StringBuffer strSub1=new StringBuffer("<sub>");
StringBuffer strSub2=new StringBuffer("</sub>");
/*---------------------------第一部分-------------------------------------*/
int length1=str.length();
for(int i=0;i<length1;i++) //插入<sub>
{
if(Character.isLetter(str.charAt(i)) & Character.isDigit(str.charAt(i+1)))
{
str.insert(i+1,strSub1);
str.insert(i+7,strSub2);
}
length1=str.length()-1;
}
/*-----------------------------第二部分-----------------------------------*/
int length2=str.length();
for(int i=0;i<length2;i++) //插入<sup>
{
if((Character.isDigit(str.charAt(i)) & str.charAt(i+1)=='+') || (Character.isDigit(str.charAt(i)) & str.charAt(i+1)=='-'))
{
str.insert(i,strSup1);
str.insert(i+6,strSup2);
}
length2=str.length()-1;
}
/*------------------------------第三部分---------------------------------*/
int length3=str.length();
for(int i=0;i<length3;i++)
{
int number1=str.lastIndexOf("</sup>+");
if(number1<0 || number1>length3)
{
break;
}
else
{
str.replace(number1,number1+7,"+</sup>");
}
}
for(int i=0;i<length3;i++)
{
int number2=str.lastIndexOf("</sup>-");
if(number2<0 || number2>length3)
{
break;
}
else
{
str.replace(number2,number2+7,"-</sup>");
}
}
String strString=str.toString();
return strString;
}
}
/*--------------------
public class Example009
{
public static void main(String args[])
{
SubAndSup as=new SubAndSup();
String ss1="H2O";
String ss2=as.setString(ss1);
System.out.print(ss2);
}
}
打印输出:H<sub>2</sub>O
|
请发表评论