Quote the given string by replacing unprintable characters by escape sequences. - Java java.lang

Java examples for java.lang:String Quote

Description

Quote the given string by replacing unprintable characters by escape sequences.

Demo Code


//package com.java2s;

public class Main {
    /** Quote the given string by replacing unprintable characters by escape
    sequences.//from   ww  w.java 2 s . c om
                 
        From PXLab at 
        http://www.uni-mannheim.de/fakul/psycho/irtel/pxlab/index-download.html
                   
        @author Hans Irtel, with mods by Dave Voorhis
        @version 0.1.9

    @param s the string to be quoted.
    @return a string which is a quoted representation of the input
    string. */
    public static String quote(String s) {
        char[] in = s.toCharArray();
        int n = in.length;
        StringBuffer out = new StringBuffer(n);
        for (int i = 0; i < n; i++) {
            switch (in[i]) {
            case '\n':
                out.append("\\n");
                break;
            case '\t':
                out.append("\\t");
                break;
            case '\b':
                out.append("\\b");
                break;
            case '\r':
                out.append("\\r");
                break;
            case '\f':
                out.append("\\f");
                break;
            case '\\':
                out.append("\\\\");
                break;
            case '\'':
                out.append("\\\'");
                break;
            case '\"':
                out.append("\\\"");
                break;
            default:
                out.append(new String(in, i, 1));
                break;
            }
        }
        return (out.toString());
    }
}

Related Tutorials