public class  ReplaceTest 
{
public static void main(String[] args) 
{
String s1="xyzAbabABdem";
StringBuffer s2=new StringBuffer();
char temp[]=s1.toCharArray();
for(int i=0;i<s1.length(); i++)
{
if((temp[i] =='a' ||temp[i] =='A' ) && (temp[i+1] =='b' ||temp[i+1] =='B' ) )
{
s2.append("new");
i=i+1; //因为"ab"是两个字符,要加1 !
System.out.println("Hello World!");
}
else
{
s2.append(temp[i]);
}
}
System.out.println(s1);
System.out.println(s2);
System.out.println("Hello World!");
}
}

解决方案 »

  1.   

    temp[i] =='a' ||temp[i] =='A' ) && (temp[i+1] =='b' ||temp[i+1] =='B' ) 这部分如果用一个函数实现,应该可用性能好点! 以替换字符和temp[i] 为参数, 哈哈
      

  2.   

    再up以下:
    Vbscript 中的replace函数的最后一个参数可以设定比较是“二进制比较”还是“文本比较”
    <script language="vbscript">
    sub a()
    dim b
    b="abcABCaBcAbc"
    b=Replace (b,"ab","new",1,-1,1)
    end sub
    </script>
    jsp中有这样的函数吗?
      

  3.   

    replaceAll函数也是用的正则表达式
    可以直接替换
    <%
    String A="xyzAbabABdem";
    A=A.replaceAll("ab|aB|Ab|AB","new");
    out.println(A);
    %>
      

  4.   

    <%!
    public String replace(String strSource,String strFrom,String strTo)
    {
    if (strSource!=null)  {
    String strDest = "";
    int intFromLen = strFrom.length();
    int intPos; while((intPos=strSource.indexOf(strFrom))!=-1)
    {
    strDest = strDest + strSource.substring(0,intPos);
    strDest = strDest + strTo;
    strSource = strSource.substring(intPos+intFromLen);
    }
    strDest = strDest + strSource; return strDest;
        } else return ("nothing");
    }
    %>
      

  5.   

    <%!
    public String replace(String strSource,String strFrom,String strTo)
    {
    if (strSource!=null)  {
    String strDest = "";
    int intFromLen = strFrom.length();
    int intPos; while((intPos=strSource.indexOf(strFrom))!=-1)
    {
    strDest = strDest + strSource.substring(0,intPos);
    strDest = strDest + strTo;
    strSource = strSource.substring(intPos+intFromLen);
    }
    strDest = strDest + strSource; return strDest;
        } else return ("nothing");
    }
    %>