user316602
user316602

Reputation:

See if a string begins with whitespace in Java

I know that trim removes whitespace from the beginning and end of a string, but I wanted to check if the first character of a string is a whitespace. I've tried what seems about everything, but I can't seem to get it to work.

Can someone point me in the right direction? I'd appreciate it if regular expressions were not used.

Thanks a lot!

Upvotes: 5

Views: 14172

Answers (4)

sanssucre
sanssucre

Reputation: 17

"string".startsWith(" ")

Upvotes: 0

digiarnie
digiarnie

Reputation: 23465

public void yourMethod(String string) {
    if (isLengthGreaterThanZero(string) && isFirstCharacterWhiteSpace(string)) {
        ...
    }
}

private boolean isFirstCharacterWhiteSpace(String string) {
    char firstCharacter = string.charAt(0);
    return Character.isWhitespace(firstCharacter);
}

private boolean isLengthGreaterThanZero(String string) {
    return string != null && string.length() > 0;
}

Upvotes: 0

maerics
maerics

Reputation: 156652

if (Character.isWhitespace(str.charAt(0))) //...

Upvotes: 4

casablanca
casablanca

Reputation: 70721

if (Character.isWhitespace(str.charAt(0))) {
  // do something
}

Upvotes: 26

Related Questions