Java 统计一句话中相同单词的个数 要求的运行结果如下:how many incher are in 2 meters?words occurence-----------------------------------are 1how 1in 1inches 1many 1meters 1
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/15 19:58:09
Java 统计一句话中相同单词的个数 要求的运行结果如下:how many incher are in 2 meters?words occurence-----------------------------------are 1how 1in 1inches 1many 1meters 1
Java 统计一句话中相同单词的个数
要求的运行结果如下:
how many incher are in 2 meters?
words occurence
-----------------------------------
are 1
how 1
in 1
inches 1
many 1
meters 1
Java 统计一句话中相同单词的个数 要求的运行结果如下:how many incher are in 2 meters?words occurence-----------------------------------are 1how 1in 1inches 1many 1meters 1
简单地写了一个类,只有一个方法和一个主函数,实现了你要求的功能:
其中countWords(List list,String substr)方法,是统计某个单词在句子中的次数的.
希望对你有所帮助.
代码如下:
package com.yss.string;
import java.util.ArrayList;
import java.util.List;
public class StringTest {
\x09/**
\x09 * @param args
\x09 */
\x09public static void main(String[] args) {
\x09\x09StringTest st=new StringTest();
\x09 String str="how many inches are in 2 meters?";
\x09 String[] sstr=str.split(" ");
\x09 List list=new ArrayList();
\x09 for(int i=0;i-1){
\x09 \x09\x09strTemp=strTemp.substring(0,strTemp.indexOf("?"));
\x09 \x09}
\x09 \x09list.add(strTemp);
\x09 }
\x09 System.out.println(sstr.length);
\x09\x09System.out.println("words\toccurence");
\x09\x09System.out.println("are\t"+st.countWords(list,"are"));
\x09\x09System.out.println("how\t"+st.countWords(list,"how"));
\x09\x09System.out.println("in\t"+st.countWords(list,"in"));
\x09\x09System.out.println("inches\t"+st.countWords(list,"inches"));
\x09\x09System.out.println("many\t"+st.countWords(list,"many"));
\x09\x09System.out.println("meters\t"+st.countWords(list,"meters"));
\x09}
\x09
\x09public int countWords(List list,String substr){
\x09\x09int num=0;
\x09\x09for(int i=0;i