如何在字符串中等于单个字符然后计算它

时间:2014-01-27 19:20:43

标签: java string equals

“这是我的代码”

public static void main(String[] args) {

    int letter_count = 0;
    String  check_word = new String ("How to equals a single character in string and then calculate it ");
    String single_letter = " ";
    int i = 0;

    for ( i = 0; i < check_word.length(); i++ ) {

        single_letter = check_word.substring(0);

        if (single_letter.equals("a") ); {
            letter_count ++;

        }
    }
    System.out.println ( " - \"a\""  + " was found " + letter_count + " times");
}

4 个答案:

答案 0 :(得分:4)

您似乎对子字符串函数的作用感到困惑。这一行:

single_letter = check_word.substring(0);

基本上返回整个check_word并将其存储在single_letter内。我怀疑你真正想要的是这个:

single_letter = check_word.substring(i, i + 1);

获得该位置的单个字母。

您也可以将其更改为:

if(check_word.charAt(i) == 'a') {
    letter_count++;
}

答案 1 :(得分:2)

您的一个问题是,;条件之后有if (single_letter.equals("a") ),因此您的代码

if (single_letter.equals("a") ); {
    letter_count ++;
}

实际上与

相同
if (single_letter.equals("a") ){
    //empty block "executed" conditionally 
}
//block executed regardless of result in `if` condition
{
    letter_count ++;
}

其他问题是

single_letter = check_word.substring(0);

将从索引check_word获取0的子字符串,这意味着它将存储与check_word相同的字符串。请考虑将charAt方法与i一起使用,而不是0。这将返回简单的char,因此您需要将其与== check_word.charAt(i)=='a'进行比较。

其他(可能更好)的方法是用

迭代字符串的所有字符
for (char ch : check_word.toCharArray()){
    //test value of ch
}

答案 2 :(得分:0)

尝试...

public static void main(String[] args) {

    int letter_count = 0;
    char[] check_word = "How to equals a single character in string and then calculate it "
            .toCharArray();
    char single_letter = 'a';

    for (int i = 0; i < check_word.length; i++) {
        if (single_letter == check_word[i]) {
            letter_count++;
        }
    }
    System.out.println(" - \"a\"" + " was found " + letter_count + " times");

}

答案 3 :(得分:0)

为什么不使用像这样的角色:

public static void main(String[] args) {

    int letter_count = 0;
    String  check_word = new String ("How to equals a single character in string and then calculate it ");
    char toCheck = 'a';

    for (int i = 0; i < check_word.length(); i++) {
        char cursor = check_word.charAt(i);
        if (cursor == toCheck) {
            letter_count++;
        }
    }
    System.out.println ( " - \"a\""  + " was found " + letter_count + " times");
}
相关问题