Josephine
Josephine

Reputation: 261

Check For Leading/Trailing Whitespaces

I'm trying to write a function that checks for leading and trailing whitespaces. It shouldn't remove them, just check to see if they exist. I wrote this:

  public static String checkWhitespace(String str)
  {
      if(str.charAt(0) == ' ' || str.charAt(str.length()-1) == ' ');
            return "invalid";
  } 

But it's catching everything. I tried using "\\s+" as the key but it's a string and it's only letting me check for chars. Any help would be awesome!

Upvotes: 2

Views: 10745

Answers (3)

Reimeus
Reimeus

Reputation: 159784

You could do

return str.trim().equals(str) ? "valid": "invalid";

Upvotes: 17

Ian Dallas
Ian Dallas

Reputation: 12741

The reason "\\s+" does not work is because you need to be using Java's Regex Matcher\Pattern classes to be checking with a regex.

String input = "   blah   ";
String regexLeadingWhitespace = "\\s+.*";
String regexTrailingWhitespace = ".*\\s+";

boolean leadingMatches = Pattern.matches(regexLeadingWhitespace, input);
boolean trailingMatches = Pattern.matches(regexTrailingWhitespace, input);

Disclaimer: I think my regexes are correct but I could be wrong, I haven't had a chance to test them out yet.

Java Regex Matacher Tutorial

Upvotes: 0

Eric Andres
Eric Andres

Reputation: 3417

You can use Character.isWhitespace instead of the "\\s+" regex you suggested.

public static String checkWhitespace(String str) {
    if (Character.isWhitespace(str.charAt(0)) || Character.isWhitespace(str.charAt(str.length() - 1))) {
        return "invalid";
    }
}

By the way, the semicolon at the end of the if statement might be what's tripping you up. That would cause it to always execute return "invalid".

Upvotes: 4

Related Questions