How can I check if a string contains anything other than whitespace?
This code didn't work:
String string = " \n\n\t\t ";
if(string.length()==0) doSomething();
since spaces and new lines have values.
Can anyone tell me how can I do it?
Note: minSDKVersion = 5
Regards :)
1. String isBlank() Method. This method returns true if the given string is empty or contains only white space code points, otherwise false . It uses Character.
To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 .
We consider a string to be empty if it's either null or a string without any length. If a string only consists of whitespace, then we call it blank. For Java, whitespaces are characters, like spaces, tabs, and so on.
Try this:
if (string.trim().length() == 0) { /* all white space */ }
Alternatively, you can use a regular expression:
if (string.matches("\\w*")) { . . . }
try:
if (string == null || TextUtils.isEmpty(string.trim()) doSomething();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With