Java String Sanitize sanitizeInput(String input)

Here you can find the source of sanitizeInput(String input)

Description

"Sanitizes" the given input by replacing any new line characters with spaces.

License

Open Source License

Parameter

Parameter Description
input a parameter
forbiddenChars a parameter
replacement a parameter

Declaration

public static String sanitizeInput(String input) 

Method Source Code

//package com.java2s;
/*//ww w .ja  va  2 s  .c  o  m
 * YAJHFC - Yet another Java Hylafax client
 * Copyright (C) 2005-2007 Jonas Wolz
 *
 * 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.
 */

public class Main {
    /**
     * "Sanitizes" the given input by replacing any new line characters with spaces.
     * @param input
     * @param forbiddenChars
     * @param replacement
     */
    public static String sanitizeInput(String input) {
        return sanitizeInput(input, "\r\n", ' ', 255);
    }

    /**
     * "Sanitizes" the given input by replacing all characters in forbiddenChars with replacement
     * @param input the input string
     * @param forbiddenChars chars to filter out
     * @param replacement char to replace filtered chars with
     * @param maxLen the maximum allowed length of the output or 0 for unlimited length 
     */
    public static String sanitizeInput(String input, String forbiddenChars, char replacement, int maxLen) {
        if (input == null)
            return null;
        if (maxLen > 0 && input.length() > maxLen)
            input = input.substring(0, maxLen);

        char[] chars = input.toCharArray();
        boolean changed = false;
        for (int i = 0; i < chars.length; i++) {
            if (forbiddenChars.indexOf(chars[i]) >= 0) {
                chars[i] = replacement;
                changed = true;
            }
        }

        if (changed) {
            return new String(chars);
        } else {
            return input;
        }
    }
}

Related

  1. sanitizeHeader(String header)
  2. sanitizeID(String name)
  3. sanitizeIdentifier(String identifier)
  4. sanitizeIdentifierName(String input)
  5. sanitizeIDs(String str)
  6. sanitizeInput(String string)
  7. sanitizeJavascript(String originalString)
  8. sanitizeLine(String line)
  9. sanitizeLineSpaces(String line)