Get the number of occurrences of a certain character in a String string

Article directory


The implementation logic is very simple:
1. First record the total length of the string.
2. Replace the character you want to judge with "" in the string.
3. Subtract the replaced length from the total length. The result is equal to the number of times the character appears. .

Assuming the following string, I want to know the number of times character a appears.
String str = "aaabbbccc"; without further explanation, just look at the code.

/*判断某字符串中某字符出现的次数*/
    @Test
    public void charNumber() {
    
    

        String str = "aaabbbccc";

        /*获取初始字符串长度*/
        int a = str.length();
        
        /*String.replace(s1,s2)方法作用:将字符串中s1替换为s2
        将其中字符a替换为”“*/
        String s = str.replace("a", "");

        /*替换后的字符串长度*/
        int b = s.length();

        System.out.println("原字符串:"+str);
        System.out.println("替换后字符串:"+s);
        System.out.println("字符a出现的次数:"+(a - b));
    }

Results of the:

Insert image description here

There are two kinds of knowledge, the kind you know and the kind you know where to find.

Guess you like

Origin blog.csdn.net/weixin_45377770/article/details/109718463