tusharRawat
tusharRawat

Reputation: 657

How best to determine if a String contains only null characters?

What's the right way to check if a string contains null characters only?

String s = "\u0000";
if(s.charAt(0) == 0) {
   System.out.println("null characters only");
}

Or

String s = "\0\0";
for(int i = 0; i < s.length(); i++) {
   if(s.charAt(i) == 0) 
       continue;

   else break;

}

Both work. But is there a better and more concise way to perform this check. Is there a utility to check if a string in java contains only null characters(\u0000 OR \0) ?

And what is the difference between '\0' and '\u0000'?

Upvotes: 5

Views: 1756

Answers (7)

mginius
mginius

Reputation: 104

Other than the other answers (all valids), I've just found a one liner, based on org.apache.commons.lang3.StringUtils:

StringUtils.containsOnly(<string>, '\u0000')

Just a note: this method manages the empty string "" returning true.

Upvotes: 0

Richard Onslow Roper
Richard Onslow Roper

Reputation: 6855

I do not think there is a predefined way to check it, and I think the second one you mentioned is the correct way of testing for the same

Upvotes: 0

user15793316
user15793316

Reputation:

You can use a regular expression

to match one or more \u0000

boolean onlyNulls = string.matches("\u0000+");  // or "\0+"

use * instead of + to also match the empty string


(the stream solution by Sweeper is my preferred solution - IMHO it better resembles the intended task, despite I would use '\u0000' instead of 0)

Upvotes: 3

Luca
Luca

Reputation: 56

\u0000 is Unicode value , The console output is a space

Stream.of("\u0000","\0\0","jack", "luca")
  .filter(s -> !s.trim().equals(""))
  .forEach(System.out::println);

output:

jack
luca

Upvotes: -1

Meetesh
Meetesh

Reputation: 182

You can use the existing String methods like trim and isEmpty with combination for this. consider this:

String s = "\u0000";
s.trim().isBlank()

Upvotes: -1

Sweeper
Sweeper

Reputation: 272370

You can get the chars() as an IntStream, then use allMatch:

if (yourString.chars().allMatch(x -> x == 0)) {
    // all null chars!
}

Upvotes: 5

Elliott Frisch
Elliott Frisch

Reputation: 201477

A char literal (in Java) can be written multiple ways (all of which are equivalent). For example,

System.out.println('\u0000' == '\0');
System.out.println('\u0000' == 0);

Will output

true
true

because a char is a 16-bit integral type in Java. And all three of \u0000, \0 and 0 are the same value. As for finding if a String contains only 0 char values - simply iterate it. Like,

boolean allNulls = true;
for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) != 0) {
        allNulls = false;
        break;
    }
}

Upvotes: 9

Related Questions