How to check that a Java String is not all whitespaces?

How to check that a Java String is not all whitespaces?

To check if a Java String is not composed entirely of whitespace characters, you can use a regular expression or a simple loop. Here are two common approaches:

  1. Using Regular Expression:

    You can use a regular expression to check if the string contains at least one non-whitespace character. Here's how you can do it:

    public static boolean isNotBlank(String str) { return str != null && !str.trim().isEmpty(); } 

    This method first checks if the string is not null to avoid a NullPointerException. Then, it trims the string to remove leading and trailing whitespace characters using trim(). Finally, it checks if the trimmed string is not empty.

    Usage:

    String text = " Hello, World! "; boolean result = isNotBlank(text); System.out.println("Is the string not all whitespace? " + result); 
  2. Using a Loop:

    You can also use a simple loop to check if the string contains at least one non-whitespace character. Here's an example:

    public static boolean isNotBlank(String str) { if (str == null) { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } 

    This method iterates through each character in the string and checks if it's not a whitespace character using Character.isWhitespace().

    Usage is the same as in the previous example.

Both of these methods will return true if the string contains at least one non-whitespace character and false if it is composed entirely of whitespace characters or is null. Choose the method that best fits your code and coding style.


More Tags

azure-synapse garbage-collection theano sendgrid yup tab-completion jsse mediacontroller tkinter spawn

More Java Questions

More Cat Calculators

More Fitness-Health Calculators

More Housing Building Calculators

More Date and Time Calculators