2007-09-02

使用java转换"&","<",">",""","'"的实现

关键字: 编程基础
这里主要对&,<,>,",'进行转化,程序使用Java实现,方法分为两个encode和decode:

1,encode的方法实现如下,主要是把&转化为&等
public static String encode(String text) {
        char c;
        StringBuffer n = new StringBuffer();
        for (int i = 0; i < text.length(); i++) {
            c = text.charAt(i);
            switch (c) {
                case '&':
                    {
                        n.append("&");
                        break;
                    }
                case '<':
                    {
                        n.append("<");
                        break;
                    }
                case '>':
                    {
                        n.append(">");
                        break;
                    }
                case '"':
                    {
                        n.append(""");
                        break;
                    }
                case '\'':
                    {
                        n.append("'");
                        break;
                    }
                default :
                    {
                        n.append(c);
                        break;
                    }
            }
        }
        return new String(n);
    }

2,主要实现对encode的逆
	public static String decode(String text) {
        char c, c1, c2, c3, c4, c5;
        StringBuffer n = new StringBuffer();
        for (int i = 0; i < text.length(); i++) {
            c = text.charAt(i);
            if (c == '&') {
                c1 = text.charAt(i + 1);
                c2 = text.charAt(i + 2);
                c3 = text.charAt(i + 3);
                c4 = text.charAt(i + 4);
                c5 = text.charAt(i + 5);

                if (c1 == 'a' && c2 == 'm' && c3 == 'p' && c4 == ';') {
                    n.append("&");
                    i += 5;
                }
                else if (c1 == 'l' && c2 == 't' && c3 == ';') {
                    n.append("<");
                    i += 4;
                }
                else if (c1 == 'g' && c2 == 't' && c3 == ';') {
                    n.append(">");
                    i += 4;
                }
                else if (c1 == 'q' && c2 == 'u' && c3 == 'o' &&
                    c4 == 't' && c5 == ';') {
                    n.append("\"");
                    i += 6;
                }
                else if (c1 == 'a' && c2 == 'p' && c3 == 'o' &&
                    c4 == 's' && c5 == ';') {
                    n.append("'");
                    i += 6;
                }
                else
                    n.append("&");
            }
            else
                n.append(c);
        }
        return new String(n);
    }
评论
发表评论

您还没有登录,请登录后发表评论