Checking Spaces and Errors

I am looking for an if statement to check if the input string is empty or consists only of spaces and if the next input is not continued. Below is my code that gives an error when entering spaces.

    name = name.trim().substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
    if(name != null && !name.isEmpty() && name.contains(" ")) {
        System.out.println("One");
    } else {
        System.out.println("Two");
    }
+4
source share
3 answers

I would write this as the following.

name = name == null ? "" : name.trim();
if(name.isEmpty()) {
    System.out.println("Null, empty, or white space only name received");
} else {
    System.out.println("Name with at least length one received");
    name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
}
+1
source

The reason it gives you an error is because trim () removes all the leading and trailing spaces [edited], so your line is empty. At this point, you call the substring (0,1), so it will be out of range.

+5
source

, String, matches(regex), , .

, ...

String emptyOrAllWhiteSpace = "^[ \t]*$";
if (name == null || name.matches(emptyOrAllWhiteSpace)) {
    // first thing.
} else {
    // second thing.
}

Apache Commons Lang - StringUtils.isEmpty(CharSequence), StringUtils.isWhitespace(CharSequence).

Guava has another helper Strings.isNullOrEmpty()that you can use.

0
source

Source: https://habr.com/ru/post/1621911/


All Articles