Unquote the given string and replace escape sequences by the original characters. - Java java.lang

Java examples for java.lang:String Quote

Description

Unquote the given string and replace escape sequences by the original characters.

Demo Code


//package com.java2s;

public class Main {
    /** Unquote the given string and replace escape sequences by the
        original characters. /*from   w w w.  j  av a 2  s .  co  m*/
                 
        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 unquoted.
    @return a string with quotes removed and escape sequences
    replaced by the respective character codes. */
    public static String unquote(String s) {
        char[] in = s.toCharArray();
        char[] out = new char[in.length];
        boolean inEscape = false;
        int k = 0;
        int n = in.length;
        for (int i = 0; i < n; i++) {
            if (inEscape) {
                switch (in[i]) {
                case 'n':
                    out[k++] = '\n';
                    break;
                case 't':
                    out[k++] = '\t';
                    break;
                case 'b':
                    out[k++] = '\b';
                    break;
                case 'r':
                    out[k++] = '\r';
                    break;
                case 'f':
                    out[k++] = '\f';
                    break;
                case '\\':
                    out[k++] = '\\';
                    break;
                case '\'':
                    out[k++] = '\'';
                    break;
                case '\"':
                    out[k++] = '\"';
                    break;
                default:
                    out[k++] = '\\';
                    out[k++] = in[i];
                    break;
                }
                inEscape = false;
            } else {
                if (in[i] == '\\') {
                    inEscape = true;
                } else {
                    out[k++] = in[i];
                }
            }
        }
        return (new String(out, 0, k));
    }
}

Related Tutorials