Java String Sanitize sanitizeString(String str)

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

Description

Escapes all escapable characters in a string.

License

Open Source License

Parameter

Parameter Description
str The string to iterate through and escape character

Exception

Parameter Description
Exception Throws an Exception if an invalid escaped character is found in the string.

Return

A String, similar to the argument but with all appropriate character pairs escaped.

Declaration

public static String sanitizeString(String str) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//w w w .j a  v a2s .  c o  m
     * Escapes all escapable characters in a string.
     * 
     * @param str The string to iterate through and escape character
     * @return A String, similar to the argument but with all appropriate character pairs escaped.
     * @throws Exception Throws an Exception if an invalid escaped character is found in the string.
     */
    public static String sanitizeString(String str) throws Exception {
        String newStr = "";
        boolean escape = false;

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            if (escape) {
                switch (c) {
                case '\\':
                    newStr += "\\";
                    break;
                case '\"':
                    newStr += "\"";
                    break;
                case 'n':
                    newStr += "\n";
                    break;
                case 'r':
                    newStr += "\r";
                    break;
                case 'f':
                    newStr += "\f";
                    break;
                case 'b':
                    newStr += "\b";
                    break;
                case 't':
                    newStr += "\t";
                    break;
                default:
                    throw new Exception("Invalid escape character in string.");
                }
                escape = false;
            } else if (c == '\\') {
                escape = true;
            } else {
                newStr += c;
            }
        }
        return newStr;
    }
}

Related

  1. sanitizeString(String dirtyString)
  2. sanitizeString(String input)
  3. sanitizeString(String s)
  4. sanitizeString(String s)
  5. sanitizeString(String s)
  6. sanitizeStringAsLiteral(String literal)
  7. sanitizeStringForXPath(String text)
  8. sanitizeStringLiteral(String inputString)
  9. sanitizeSuiteName(String name)