题目描述
给定一串字符串(英文段落),用户输入某个单词,求该单词出现的总次数,和出现在第几个位置上。
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()*方法判断是否还有未分析的部分。