使用Java来实现统计单词出现的次数两种方法

该代码示例展示了如何在Java中计算一个字符串中特定单词的出现次数。通过split方法将字符串分解为单词数组,然后遍历数组并比较每个单词,实现对目标单词的计数功能。
public class Numberofwords {
    public static void main(String[] args) {
        String str = "Hello World abc Hello hello";
        // 截取字符串 第一个包含的 第二个不包含
       Numberofwords test = new Numberofwords();
        int count = test.wordCount(str,"hello");
        System.out.println(count);
//        String str ="hello hello wrod wrod wrod wrod wrod wrod hello";
//         String str1 = "hello";
//        String replace = str.replace(str1, "");
//        int replaceTest = str.length() - replace.length();
//        int count = replaceTest / str1.length();
//        System.out.println(count);
    }


    public int wordCount(String Test, String word) {//返回值为文章和所选定的单词
        // 1、先把文章打散成数组
      String[] st= Test.split(" ");//文章遇见空格时,分成一个数组,遇到空格时分成一个数组,从而把文章分为一个一个的数组。
      int res = 0;
        for (int i = 0; i < st.length; i++) {
            if (st[i].equalsIgnoreCase(word)){//判断数组是否等于所选择的词语
                res++;
            }

        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值