How to check if a char is equal to an empty space?

2019-01-10 05:16发布

Here's what I've got:

private static int countNumChars(String s) {
    for(char c : s.toCharArray()){
        if (Equals(c," "))
    }
}

But that code says it cannot find Symbol for that method. I remember Java having a comparer like this... Any suggestions?

11条回答
做自己的国王
2楼-- · 2019-01-10 05:29

To compare Strings you have to use the equals keyword.

if(c.equals(""))
{
}
查看更多
别忘想泡老子
3楼-- · 2019-01-10 05:30

Since char is a primitive type, you can just write c == ' '.
You only need to call equals() for reference types like String or Character.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-10 05:36

You can try:

if(Character.isSpaceChar(ch))
{
    // Do something...
}

Or:

if((int) ch) == 32)
{
    // Do something...
}
查看更多
太酷不给撩
5楼-- · 2019-01-10 05:37
if (c == ' ')

char is a primitive data type, so it can be compared with ==.

Also, by using double quotes you create String constant (" "), while with single quotes it's a char constant (' ').

查看更多
Evening l夕情丶
6楼-- · 2019-01-10 05:40

In this case, you are thinking of the String comparing function "String".equals("some_text"). Chars do not need to use this function. Instead a standard == comparison operator will suffice.

private static int countNumChars(String s) {
    for(char c : s.toCharArray()){
        if (c == ' ') // your resulting outcome
    }
}
查看更多
Melony?
7楼-- · 2019-01-10 05:44

My suggestion would be:

if (c == ' ')
查看更多
登录 后发表回答