Reputation: 261
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
Reputation: 159784
You could do
return str.trim().equals(str) ? "valid": "invalid";
Upvotes: 17
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.
Upvotes: 0
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