Java提取字符串中特有词次数

从"helloworld hellomoon hellosun hello lamp post";找出hello出现的次数。应该是4.
设置一个bioolean,如果是"helloworld hellomoon hellosun HELLO lamp post"; 或者变成HeLLo Hello又应该怎么去判断。

通过字符串的拆分也可以实现


String str = "helloworld hellomoon hellosun hello lamp post";
String[] s =  str.split("hello");
// str会将hello作为拆分条件,总共拆分hello出现的次数+1
System.out.println("hello出现:"+(s.length - 1)+"次");
str = "helloworld hEllollomoon helLosun hello lahellomp post";
// 将字符串和截取字符串转小写或大写就一样了
s =  str.toLowerCase().split("hElLo".toLowerCase());
System.out.println("hello出现:"+(s.length - 1)+"次");

img

遍历整个字符串,从遍历到'h'开始连续的五个字符与hello相同,则计数+1;否则继续遍历
比较就直接=='h' =='e'之类的

大小写不同的那种,你可以用toUpperCase()函数把两个字符串中的字母都转成大(小)写,后面挨个对比,匹配到第一个字符就开始匹配剩下的。
参考:

public class Main {
    public static void main(String[] args) {
        String n = "helloworld hellomoon hellosun HELLO lamp post";
        String m = "hello";
        n = n.toUpperCase();
        m = m.toUpperCase();
        int idex = 0; //遍历字符串
        int count = 0; //统计次数
        for(; idex < n.length(); ) {
            if(n.indexOf(m,idex) != n.lastIndexOf(m)) {//如果开头找到的子串和结尾找到的子串位置不一样,则计数器count+1
                idex += n.indexOf(m,idex);
                count++;
            }
        }
        count++;
        System.out.println("子串重复出现了"+count+"次");
    }
}

或者你可以按照第二个字符串将第一个分割,分割的字符串数-1就是它出现的次数

public class Main {
    public static void main(String[] args) {
        String n = "helloworld hellomoon hellosun HELLO lamp post";
        String m = "hello";
        n = " "+n.toUpperCase()+" ";    //防止m出现在首尾
        m = m.toUpperCase();
        String[] str =  n.split(m);
        System.out.println(m + "重复出现了:" + (str.length-1)+"次");
    }
}

img

这个是一样的,只是大小写不同而已

用拆分、替换、遍历字符串都行;如果严格要求大小写一样就不转换,如果不要求大小写就都先统一转为大小或小写;

拆分的上面都有了,给个替换的

        String s = "helloworld hellomoon hellosun hello lamp post";
        String p = "hello";
        // 不要求大小写就转一下
//        s = s.toLowerCase();
//        p = p.toLowerCase();
        String replace = s.replace(p, "");
        int t = (s.length() - replace.length()) / p.length();

        System.out.println(t);

先整体转大小写.然后直接统计,用了hutool工具类
package cn.hutool.core.util;
String s = "helloworld hellomoon hellosun HELLO lamp post";
int count = StrUtil.count(s.toLowerCase(),"hello");
System.out.println(count);

标准的解法不应该是使用正则表达式吗,效率更高