Check if a string has a white space at any position

by Dr. Osama M. Khaled last modified 2022-07-19T05:23:42+01:00
It is important sometimes to check a string and make sure that it does contain a white space (e.g. space, new line, tab, etc ...).

However, I did not see a function in Java that takes a string and return true or false if there is a white space.

I developed this function to help out with that objective

public static boolean hasWhiteSpace(String text) {
boolean noWhite = false;
if (text == null)
return noWhite;
for (int i = 0; i < text.length(); i++ ) {
if (Character.isWhitespace(text.charAt(i)))
noWhite = true;
break;
}
return noWhite;
}

As you see, the assumption is that if the string is null, then it does not include a white space,

and if there is a single white space at any character position, then the function breaks and returns

true