Open In App

Program to check if a String in Java contains only whitespaces

Given a string str, the task is to check if this string contains only whitespaces or some text, in Java.

Examples:



Input: str = "              " 
Output: True

Input: str = "GFG"
Output: False

Approach:

Below is the implementation of the above approach:




// Java Program to check if
// the String is not all whitespaces
  
class GFG {
  
    // Function to check if the String is all whitespaces
    public static boolean isStringAllWhiteSpace(String str)
    {
  
        // Remove the leading whitespaces using trim()
        // and then check if this string is empty
        if (str.trim().isEmpty())
            return true;
        else
            return false;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "GeeksforGeeks";
        String str2 = "              ";
  
        System.out.println("Is string [" + str1
                           + "] only whitespaces? "
                           + isStringAllWhiteSpace(str1));
        System.out.println("Is string [" + str2
                           + "] only whitespaces? "
                           + isStringAllWhiteSpace(str2));
    }
}

Output:
Is string [GeeksforGeeks] only whitespaces? false
Is string [              ] only whitespaces? true

Article Tags :