在String中计算char

时间:2012-02-21 01:14:16

标签: java

我是Java的新手,我想知道如何计算字符串lHello的数量? 任何帮助都将非常感激。

public int countChar(String s, char c)
{   
    String st= s;
    char ch =c;
    int counter = 0;
    for( int i=0; i<st.length(); i++ )
    {
        if( st.charAt(i) == ch ) 
        {
            counter++;
        } 
    }       
    return counter;
}

public static void main(String[] args)
{ 
    new Loop().countChar("Hello", 'l');         
}

3 个答案:

答案 0 :(得分:2)

这应该按预期工作 - 如果要打印结果,请将main更改为:

public static void main(String[] args)
{ 
    int count = new Loop().countChar("Hello", 'l');
    System.out.println("The count is: " + count);
}

答案 1 :(得分:0)

尝试使用以下代码:

公共类CharacterCout {

public static int getCharacterCount(String string, char character) {
    int counter = 0;
    for(int i=0;i<string.length();i++) {
        if(string.charAt(i)==character){
            counter++;
        }
    }
    return counter;
}

public static void main(String[] args) {
    String string = "Hello World!";
    char character = 'l';
    System.out.println("Character "+character+" count: " +getCharacterCount(string, character));
}

}

答案 2 :(得分:0)

public String twoOccurrences(String stringa, char stringb) {
    int counter = 0;
    for (int i = 0; i < stringa.length(); i++) {
        if (stringa.charAt(i) == stringb) {
            counter++;
        }
    }
    if (counter >= 1) {
        return "" + counter;
    } else {
        return "There is no matching letters";
    }
}

public void testOcurrences() {
    char stringb = 'a';
    String stringa = "Banana";
    System.out.println("String a is :" + stringa);
    System.out.println("String b is :" + stringb);
    String occurrence = twoOccurrences(stringa, stringb);
    System.out.println("There is " + occurrence + " '" + stringb + "' in " + stringa);
}

}