java 分析英文段落,查找、统计单词

题目描述

给定一串字符串(英文段落),用户输入某个单词,求该单词出现的总次数,和出现在第几个位置上。

import java.util.*;
//主程序
public class WordSearch {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Please enter an English sentence:"); 
        String s = reader.nextLine();//接收句子
        System.out.println("Please enter the word you want to search:");
        String x = reader.nextLine();//接收单词
        Sentence sentence = new Sentence(s);//实例化Sentence对象
        System.out.println("The total number word"+" \""+x+"\" "+"appears is:"+sentence.getCount(x));
        if(sentence.getCount(x)!=0) {
            System.out.print("Its location(s) are:");
            sentence.getLocation(x);
        }
    }
}

class Sentence{
    String s;
    String regex = "[\\s\\d\\p{Punct}]+";//默认regex
    Sentence(String s){
        this.s = s;
    }
    void setRegex(String regex) {
        this.regex = regex;
    }
    //运用split()方法,打印单词所在的位置,忽略大小写
    void getLocation(String word) {
        String words[] = s.split(regex);
        for(int i=0;i<words.length;i++) {
            if(words[i].equalsIgnoreCase(word)) {
                System.out.print(" "+i);
            }
        }
    }
    //运用StringTokenizer类,得到单词出现的次数,忽略大小写
    int getCount(String word) {
        s = s.replaceAll(regex, "#");
        StringTokenizer fenxi = new StringTokenizer(s,"#");
        int cnt = 0;
        while(fenxi.hasMoreTokens()) {
            String tocken = fenxi.nextToken();
            if(tocken.equalsIgnoreCase(word))
                cnt = cnt + 1;         
        }
        return cnt;
    }
}

测试段落

Twinkle, twinkle, little star, How I wonder what you are. Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are. When the blazing sun is gone, When he nothing shines upon, Then you show your little light, Twinkle, twinkle, all the night.

运行效果

在这里插入图片描述

用到的方法

String类中的*split()*方法,括号中填写用作分隔符的符号或正则表达式,返回分割后的数组。

Sting类中的*equals(),equalsIgnoreCase()*方法括号中填写用来比较的字符串,判断两个字符串的内容是否一致,*equalsIgnoreCase()*忽略大小写。(“==”判断两个字符串在内存中的地址是否一致)

String类中的*replaceAll(String a,String b)*方法,a为需要替换的字符,b为需要替换成的字符,返回替换后的字符串。

StringTokenizer类的构造方法StringTokenizer(String s, String a),s为需要分析的字符串,a为分隔符,将s分割成若干部分。

StringTokenizer类的*nextToken()*方法读取下一个分割后的部分。

StringTokenizer类的*hasMoreTokens()*方法判断是否还有未分析的部分。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值