字符串转换....

该博客介绍了字符串编码器类,包含将字符串中指定子串替换、转换为 HTML 编码和 XML 编码等方法。替换子串时不使用正则表达式,而是普通字符串。对于空字符串或 null 输入,方法会直接返回空字符串。
/**
* 字符串编码器类,将字符串转换为指定格式.<br>
* <br>
* 参数字典:<br>
* src - source     来源的简写<br>
* dst - destnation 目的的简写<br>
* fnd - find       查找的简写<br>
* rep - replace    替换的简写<br>
* idx - index      索引,下标的简写<br>
* enc - encoding   编码的简写<br>
* <br>
* 例子:<br>
* <%=ArticleFormat.htmlTextEncoder(yourString)%>
*/
public class StringEncoder
{
    /**
     * 将字符串src中的子字符串fnd全部替换为新子字符串rep.<br>
     * 功能相当于java sdk 1.4的String.replaceAll方法.<br>
     * 不同之处在于查找时不是使用正则表达式而是普通字符串.
     */
    public static String replaceAll(String src, String fnd, String rep) throws Exception
    {
        if (src == null || src.equals(""))
        {
            return "";
        }
       
        String dst = src;
       
        int idx = dst.indexOf(fnd);
       
        while (idx >= 0)
        {
            dst = dst.substring(0, idx) + rep + dst.substring(idx + fnd.length(), dst.length());
            idx = dst.indexOf(fnd, idx + rep.length());
        }
       
        return dst;
    }

    /**
     * 转换为HTML编码.<br>
     */
    public static String htmlEncoder(String src) throws Exception
    {
        if (src == null || src.equals(""))
        {
            return "";
        }
       
        String dst = src;
        dst = replaceAll(dst, "<",    "&lt;");
        dst = replaceAll(dst, ">",    "&rt;");
        dst = replaceAll(dst, "/"",   "&quot;");
        dst = replaceAll(dst, "'",    "&#039;");
        dst = replaceAll(dst, " ",    "&nbsp;");
        dst = replaceAll(dst, "/r/n", "<br>");
        dst = replaceAll(dst, "/r",   "<br>");
        dst = replaceAll(dst, "/n",   "<br>");
       
        return dst;
    }


    /**
     * 转换为XML编码.<br>
     */
    public static String xmlEncoder(String src) throws Exception
    {
        if (src == null || src.equals(""))
        {
            return "";
        }
       
        String dst = src;
        dst = replaceAll(dst, "&",  "&amp;");
        dst = replaceAll(dst, "<",  "&lt;");
        dst = replaceAll(dst, ">",  "&gt;");
        dst = replaceAll(dst, "/"", "&quot;");
        dst = replaceAll(dst, "/'", "&acute;");
       
        return dst;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值