0

I have a String in Java that I want to check for whitespace and special characters excluding underscores and periods. What would be the best way to do so?

UPDATE

This is how I solved this particular problem:

            String actualString = "string";
            String testString = actualString;
            testString = testString.replaceAll("_", "");
            testString = testString.replaceAll("\\.", "");
            Pattern whiteSpaceP = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);
            Matcher whiteSpaceM = whiteSpaceP.matcher(testString);
            Pattern specCharP = Pattern.compile("\\W", Pattern.CASE_INSENSITIVE);
            Matcher specCharM = specCharP.matcher(testString);
            if(whiteSpaceM.find() || specCharM.find()) {
               System.out.println("There are spaces and non-alphanumeric characters excluding . and _ in the string");
            }
Horatio
  • 1,695
  • 1
  • 18
  • 27

3 Answers3

1

The best way to do so would be to use a Regular Expression, or Regex, or Pattern. The amount of documentation and tutorials available for regexs is so huge for all languages that I don't think it is worth saying more here. You should research the term and learn how to use them as they are an essential tool for any programmer in a wide variety of situations!

user1886323
  • 1,179
  • 7
  • 15
0

This might work for you:

for(int i =0;i<input.length(); i++){
    if(input.charAt(i).equals("_")||input.charAt(i).equals(".")){
        continue; //ignoring the character
    }
    else if(input.charAt(i).equals("#")||input.charAt(i).equals("%")||input.charAt(i).equals("&")||input.charAt(i).equals("$")){  //Add or clauses for each special character
        System.out.println("Special Character found!!");

    }
    else if(input.charAt(i).equals(" ")){
        System.out.println("White space!!");
    }

}
Pablo Estrada
  • 3,182
  • 4
  • 30
  • 74
0

You should use regular expressions with the Matcher and Pattern classes that the java library offer you, check this out it explains how to use the Pattern and Matcher class very well. http://tutorials.jenkov.com/java-regex/matcher.html#java-matcher-example

Moshe Rabaev
  • 1,892
  • 16
  • 31