Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: check if the string not only white spaces

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 :)

like image 710
Saif Hamed Avatar asked Sep 23 '13 19:09

Saif Hamed


People also ask

How do you check if string is empty with spaces?

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.

How do I check if input is only spaces?

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 .

Is an empty string white space?

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.


2 Answers

Try this:

if (string.trim().length() == 0) { /* all white space */ }

Alternatively, you can use a regular expression:

if (string.matches("\\w*")) { . . . }
like image 68
Ted Hopp Avatar answered Sep 30 '22 17:09

Ted Hopp


try:

if (string == null || TextUtils.isEmpty(string.trim()) doSomething();
like image 26
nomachinez Avatar answered Sep 30 '22 19:09

nomachinez