Java String Unescape unescape(String src)

Here you can find the source of unescape(String src)

Description

undoes the operations of escape

License

Open Source License

Declaration

public static String unescape(String src) 

Method Source Code

//package com.java2s;
/*//from  w w w .  j  a  v  a2  s . co  m
Copyright (c) 2008 Arno Haase.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
    
Contributors:
Arno Haase - initial API and implementation
 */

public class Main {
    /**
     * undoes the operations of <code>escape</code>
     */
    public static String unescape(String src) {
        if (src == null)
            return null;

        final StringBuffer result = new StringBuffer();
        for (int i = 0; i < src.length(); i++) {
            final char curChar = src.charAt(i);

            if (curChar != '\\') {
                result.append(curChar);
                continue;
            }
            // increment i to skip to the character after '\\'
            i++;
            if (i >= src.length())
                throw new IllegalArgumentException("String ends with '\\'");

            result.append(unescapeChar(src.charAt(i)));
        }

        return result.toString();
    }

    private static char unescapeChar(char escapedChar) {
        switch (escapedChar) {
        case '\\':
            return '\\';
        case 'n':
            return '\n';
        case 'r':
            return '\r';
        case 't':
            return '\t';
        case '"':
            return '"';
        }
        throw new IllegalArgumentException("unsupported string format: '\\" + escapedChar + "' is not supported.");
    }
}

Related

  1. unescape(String s, char[] charsToEscape)
  2. unescape(String s, int i)
  3. unescape(String s, String toUnescape)
  4. unescape(String source)
  5. unescape(String src)
  6. unescape(String src)
  7. unescape(String src)
  8. unescape(String st)
  9. unescape(String str)