Java Char Array Escape charsToEscapes(String str)

Here you can find the source of charsToEscapes(String str)

Description

Escapes newlines, tabs, backslashes, and quotes in the specified string.

License

Open Source License

Parameter

Parameter Description
str The string

Declaration

public static String charsToEscapes(String str) 

Method Source Code

//package com.java2s;
/**/*from  w  w  w.j  av a  2  s  .  co  m*/
 * Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and
 * www.integratedmodelling.org. 
    
   This file is part of Thinklab.
    
   Thinklab is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published
   by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.
    
   Thinklab is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.
    
   You should have received a copy of the GNU General Public License
   along with Thinklab.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Escapes newlines, tabs, backslashes, and quotes in the specified
     * string.
     * @param str The string
     * @since jEdit 2.3pre1
     */
    public static String charsToEscapes(String str) {
        return charsToEscapes(str, "\n\t\\\"'");
    }

    /**
     * Escapes the specified characters in the specified string.
     * @param str The string
     * @param toEscape Any characters that require escaping
     * @since jEdit 4.1pre3
     */
    public static String charsToEscapes(String str, String toEscape) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (toEscape.indexOf(c) != -1) {
                if (c == '\n')
                    buf.append("\\n");
                else if (c == '\t')
                    buf.append("\\t");
                else {
                    buf.append('\\');
                    buf.append(c);
                }
            } else
                buf.append(c);
        }
        return buf.toString();
    }
}

Related

  1. charsToEscapes(String str)