0

文字列内のスペースをカウントしたい:

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);
    }
}

if ステートメントを に置き換えるとif(temp.equals(" "))、"cannot invoke(String) on the Primitive type char.

これがうまくいかない理由がわかりません。

4

4 に答える 4

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);
    }
}
于 2013-01-22T22:50:30.873 に答える
1

commons-lang.jarを使用してこれを計算できます。

`パブリッククラスメイン{

public static void main(String[] args) {
    String word = "a b c";
    System.out.println("Spaces in string: " + StringUtils.countMatches(word," "));
}

} `

「StringUtils.countMatches」のソースは次のとおりです。

public static int countMatches(String str, String sub) {
    if (isEmpty(str) || isEmpty(sub)) {
        return 0;
    }
    int count = 0;
    int idx = 0;
    while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) {
        count++;
        idx += sub.length();
    }
    return count;
}
于 2013-01-23T09:15:48.173 に答える
1

String の replace 関数を使用して、すべてのスペース (" ") をスペースなし ("") に置き換え、replace 関数を呼び出す前後の長さの差を取得できます。次の例を見てください。

class Test{

    public static void main(String args[]){

        String s1 = "a b c";
        int s1_length = s1.length();
        System.out.println(s1_length); // 5

        String s2 = s1.replace(" ",""); 
        int s2_length = s2.length();
        System.out.println(s2_length); // 3

        System.out.println("No of spaces = " + (s1_length-s2_length)); // No of spaces = 2
    }
}
于 2013-01-22T23:26:14.750 に答える
0

パブリック クラス CountSpace {

public static void main(String[] args) {

    String word = "a b c";
    String data[];int k=0;
    data=word.split("");
    for(int i=0;i<data.length;i++){
        if(data[i].equals(" ")){
            k++;
        }

    }
    System.out.println(k);

}

}

于 2013-02-08T21:12:26.503 に答える