简体   繁体   English

如何比较字符以检查它是否为 null?

[英]How do I compare a character to check if it is null?

I tried the below, but Eclipse throws an error for this.我尝试了下面的方法,但是 Eclipse 会为此抛出错误。

while((s.charAt(j)== null)

What's the correct way of checking whether a character is null ?检查字符是否为null的正确方法是什么?

Check that the String s is not null before doing any character checks.在进行任何字符检查之前,请检查String s是否为null The characters returned by String#charAt are primitive char types and will never be null : String#charAt返回的字符是原始char类型,永远不会为null

if (s != null) {
  ...

If you're trying to process characters from String one at a time, you can use:如果您尝试一次处理一个String中的字符,您可以使用:

for (char c: s.toCharArray()) {
   // do stuff with char c  
}

(Unlike C , NULL terminator checking is not done in Java.) (与C不同,Java 中不进行NULL终止符检查。)

Default value to char primitives is 0 , as its ascii value. char 原语的默认值为 0 ,作为其 ascii 值。 you can check char if it is null.您可以检查 char 是否为空。 for eg:例如:

char ch[] = new char[20]; //here the whole array will be initialized with '\u0000' i.e. 0
    if((int)ch[0]==0){
        System.out.println("char is null");
    }

Correct way of checking char is actually described here .检查char正确方法实际上在这里描述。

It states:它指出:

Change it to: if(position[i][j] == 0) Each char can be compared with an int .将其更改为: if(position[i][j] == 0)每个char都可以与一个int进行比较。 The default value is '\' ie 0 for a char array element.默认值为'\'char数组元素为 0。 And that's exactly what you meant by empty cell, I assume.我想这正是你所说的空单元格的意思。

我们无法检查字符是否为空,因为字符是原始数据类型。

您可以使用空字符( '\\0' ):

while((s.charAt(j)=='\0')

I actually came here from reading a book "Java: A Beginner's Guide" because they used this solution to compare char to null:我其实是看一本书《Java: A Beginner's Guide》来到这里的,因为他们使用这个解决方案来比较 char 和 null:

(char) 0

Because in ASCII table, null is at the position of 0 in decimal.因为在ASCII表中,null在十进制为0的position处。

So, solution to OP's problem would be:因此,OP 问题的解决方案是:

while((s.charAt(j) == (char) 0)

I also tried out the already offered solution of:我还尝试了已经提供的解决方案:

while((s.charAt(j)=='\0')

And it also worked.它也奏效了。

But just wanted to add this one too, since no one mentioned it.但是也想添加这个,因为没有人提到它。

If s is a string and is not null, then you must be trying to compare "space" with char.如果s是一个字符串并且不为空,那么您必须尝试将“空间”与字符进行比较。 You think "space" is not a character and space is just null , but truth is that space is a character.你认为 "space" 不是一个字符而 space 只是null ,但事实是 space 是一个字符。 Therefore instead of null , use因此,而不是null ,使用(which is a space) to compare to character. (这是一个空格)来比较字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM