计算字符串中的空格

0 java string comparison

我想计算字符串中的空格:

public class SongApp {
    public static void main(String[] args) {
        String word = "a b c";

        int i =0,spaceCount=0;

        while(i<word.length()){

            char temp = word.charAt(i);         
            System.out.println(temp);
            if(" ".equals(temp)){
                spaceCount++;
            }
            i++;            
        }
        System.out.println("Spaces in string: "+spaceCount);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我用if替换if语句时if(temp.equals(" ")),我得到一个"无法在原始类型char上调用(String).

我不明白为什么这不起作用.

pau*_*olc 7

它不起作用,因为你在一个原始类型为'char'的值上调用Class String(equals())的方法.您正在尝试将'char'与'String'进行比较.

你必须比较'char',因为它是一个原始值你需要使用'=='布尔比较运算符,如:

public class SongApp {

    public static void main(String[] args) {

      String word = "a b c";
      int i = 0,
      spaceCount = 0;

      while( i < word.length() ){
        if( word.charAt(i) == ' ' ) {
            spaceCount++;
        }
        i++;
      }

      System.out.println("Spaces in string: "+spaceCount);
    }
}
Run Code Online (Sandbox Code Playgroud)