Droidman
Droidman

Reputation: 11608

java - check whether a string contains any characters other than spaces

I need to check if a string contains any symbols other than a space. I cant check with

      String.length() > 0

or

      String.equals("") 

since spaces are considered as characters. How can I find out whether a java String contains other characters (letters, symbols, numbers, whatever) ?

Upvotes: 1

Views: 8649

Answers (11)

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

Using Google Guava:

CharMatcher.WHITESPACE.negate().matchesAnyOf(str)

Upvotes: 2

BlueLettuce16
BlueLettuce16

Reputation: 2093

You can use StringUtils from apache commons: http://commons.apache.org/lang/api-3.1/index.html

Upvotes: 1

Andy
Andy

Reputation: 1994

With a regex:

myString.matches("[^ ]+"); // all but spaces

Upvotes: 2

Xavi López
Xavi López

Reputation: 27880

Just trim() the string (remember to check for null before invoking a method on it):

Returns a copy of the string, with leading and trailing whitespace omitted.

 myString != null && !myString.trim().isEmpty();

Or, if you're using Apache Commons, you can use StringUtils.isBlank(). You can check its implementation.

Upvotes: 6

isvforall
isvforall

Reputation: 8926

Remove all spaces:

String s = ...;
s = s.replaceAll("\\s+", "");

Then check the length:

if(s.length() > 0)

or check if a string is empty:

if (s.isEmpty())

Upvotes: 2

missrg
missrg

Reputation: 585

You could try something like this, to remove all the space characters and then to measure its length:

                string.replaceAll("\\s","")
                int length=string.length();

In this case, if length is greater than zero, it does contain non-space characters.

Hope this helps :)

Upvotes: 1

inkili
inkili

Reputation: 199

You can use

String.trim().equals("")

If String only contains spaces they all will be removed by trim() before checking for equality

Upvotes: 3

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15758

String test;
//populate test

if(test.trim().length() > 0)
{
//Bingo
}else{
//Uff
}

Upvotes: 2

user1596371
user1596371

Reputation:

Use a regular expression, "[^ ]" would do it.

Upvotes: 2

Renjith
Renjith

Reputation: 3274

Trim your string and then check it for empty string.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272247

Whyn not use String.trim() and check if the resultant length is greater than 0 ?

Upvotes: 2

Related Questions