温馨提示×

java如何查找字符串中指定字符个数

小亿
81
2024-09-26 03:29:04
栏目: 编程语言

在Java中,你可以使用以下方法来查找字符串中指定字符的个数:

public class CountCharacter {
    public static void main(String[] args) {
        String str = "hello world";
        char ch = 'l';
        int count = countCharacterOccurrences(str, ch);
        System.out.println("The character '" + ch + "' occurs " + count + " times in the string \"" + str + "\"");
    }

    public static int countCharacterOccurrences(String str, char ch) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                count++;
            }
        }
        return count;
    }
}

在这个例子中,我们定义了一个名为countCharacterOccurrences的方法,它接受一个字符串str和一个字符ch作为参数。这个方法遍历整个字符串,并在每次找到目标字符时递增计数器。最后,该方法返回计数器的值。

0