Java String Escape escape(String string, String chars)

Here you can find the source of escape(String string, String chars)

Description

escape

License

Open Source License

Declaration

static String escape(String string, String chars) 

Method Source Code


//package com.java2s;
/*//from   w ww . j av  a 2 s. co  m
   StringUtils.java
       
   Part of GridSweeper
   Copyright (c) 2006 - 2007 Ed Baskerville <software@edbaskerville.com>
    
   This program 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 2
   of the License, or (at your option) any later version.
    
   This program 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 this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

import java.io.UnsupportedEncodingException;
import java.util.*;

public class Main {
    static String escape(String string, String chars) {
        Map<String, String> replacements = new HashMap<String, String>();
        for (int i = 0; i < chars.length(); i++) {
            String original = chars.substring(i, i + 1);
            replacements.put(original, escape(original));
        }

        StringBuffer escapedStringBuilder = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            String original = string.substring(i, i + 1);
            if (replacements.containsKey(original)) {
                escapedStringBuilder.append(replacements.get(original));
            } else {
                escapedStringBuilder.append(original);
            }
        }

        return escapedStringBuilder.toString();
    }

    static String escape(String string) {
        String escapedString;
        try {
            escapedString = java.net.URLEncoder.encode(string, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
        return escapedString;
    }
}

Related

  1. escape(final String value)
  2. escape(String original)
  3. escape(String s)
  4. escape(String s)
  5. escape(String str)
  6. escapeASN1(String str)
  7. escapeCellText(String text, boolean wrap, boolean multiline)
  8. escapeCharacters(String string)
  9. escapeHTML(String s)