Converts ASCII text to HTML - Java java.lang

Java examples for java.lang:String HTML

Description

Converts ASCII text to HTML

Demo Code


//package com.java2s;

public class Main {
    /**/*from  w  ww  .j a va 2 s  .co m*/
     * Converts ASCII text to HTML
     * 
     * @param text
     * @param replacement
     * @param pre
     * @return HTML String
     */
    public static String AsciiToHtml(String text, String replacement,
            boolean pre) {
        if (text == null)
            return null;
        if (replacement == null)
            replacement = "";

        final String tabString = "   ";
        boolean space = false;
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            switch (ch) {
            case ' ':
                buffer.append((pre || !space) ? ' ' : "&nbsp;");
                space = true;
                break;
            case '\n':
                buffer.append(replacement);
                space = false;
                break;
            case '&':
                buffer.append("&amp;");
                space = false;
                break;
            case '\t':
                buffer.append(tabString);
                space = false;
                break;
            case '<':
                buffer.append("&lt;");
                space = false;
                break;
            case '>':
                buffer.append("&gt;");
                space = false;
                break;
            default:
                buffer.append(ch);
                space = false;
                break;
            }
        }
        return buffer.toString();
    }
}

Related Tutorials