如何去除HTML特殊字符并用各自的值替换特殊字符?

3
我有一个要求,需要删除HTML特殊字符,并将特殊字符替换为字符串中相应的值。

例如:

我有一个这样的字符串:

String text="Federation of AP Chambers of Commerce & Industry Awards for the year 2010-11. Speaking on the occasion, 
He said, "About 54 percent of the population is youth aged below 25 years. We have to use their energy and 
intelligence for development of the state as well as the country.The youth trained will also be absorbed by 
companies.’"

""" 需要替换为 ""","&" 需要替换为 "&","’" 需要替换为 ""。

有人可以帮我修改一下吗?我的问题中的HTML内容无法显示。 - String
我已经修改了它。另外,你到目前为止尝试了什么? - Daedalus
请参见:https://dev59.com/z3NA5IYBdhLWcg3wWseK - dimo414
2个回答

4

API中没有任何特定的方法可以做到这一点。请使用以下方法。

String text="Federation of AP Chambers of Commerce & Industry Awards for the year 2010-11. Speaking on the occasion, 
He said, "About 54 percent of the population is youth aged below 25 years. We have to use their energy and 
intelligence for development of the state as well as the country.The youth trained will also be absorbed by 
companies.’&quot";

    text= replaceAll(text,""","\"");

    text= replaceAll(text,"&","&");

    text= replaceAll(text,"’","’");




private String replaceAll(String source, String pattern, String replacement) {
        if (source == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        int index;
        int patIndex = 0;
        while ((index = source.indexOf(pattern, patIndex)) != -1) {
            sb.append(source.substring(patIndex, index));
            sb.append(replacement);
            patIndex = index + pattern.length();
        }
        sb.append(source.substring(patIndex));
        return sb.toString();
    }

3

实际上,我正在开发J2ME(Java)应用程序,Jakarta Commons Lang在J2ME中不受支持? - String

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接