Here to Learn.
Here to Learn.

Reputation: 693

Honoring space in the string while checking if it is empty

I am writing this function isEmpty(String str).

This function should behave like this:

isEmpty("")       : true
isEmpty(" ")      : false
isEmpty("abcdef") : false

I have written this function but the problem is that is not honoring the whitespace as character.

public static boolean isEmpty(String str) {
  if(str == null) {
    return true;
  }

  for(Character ch:str.toCharArray()) {
    if(Character.isWhitespace(ch)) {
        continue;
    } else {
        return false;
    }
  }
  return true;
}

Any idea where i am missing in this function?

Upvotes: 1

Views: 75

Answers (3)

Jayamohan
Jayamohan

Reputation: 12924

Have a look at this Apache commons method isEmpty(String)

This is how it behaves

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

And the implementation is as below,

public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
}

Upvotes: 1

Cory Kendall
Cory Kendall

Reputation: 7304

The answer involves these lines:

if(Character.isWhitespace(ch)) {
        continue;

You might find this link useful, if you scroll down to where they're talking about the "continue" statement. Then I would try walking through your code line by line with the String " " and see what happens.

Upvotes: 0

Tim B
Tim B

Reputation: 41178

Why don't you just do:

return str.length() == 0

Although I don't understand why you would need to write this since that's essentially what the built in String#isEmpty() method does...

The code you have written will return that a string is empty if it includes whitespace, but your description of the desired behaviour says that it needs to not include whitespace.

So either remove the whitespace check and the description is met or leave the whitespace check and the description needs fixing.

Upvotes: 6

Related Questions