java编程 在英文句子中单词出现的次数

如题所述

可以用indexOf()方法,比如你的英语句子是String str =" l love you",
截取love,那就是str.indexOf("love");返回值会是1,表示句子中有一个love
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-11-19
import java.util.Scanner;

public class Main
{
public static Scanner scanner = new Scanner(System.in);

public static void main(String[] args)
{
String sentence = scanner.nextLine();
// 用split函数切割字符串,切割符号为n个" ",算出切割后的子串个数
int len = sentence.split(" +").length;
System.out.printf("单词数为:%d",len);
}
}

第2个回答  2015-11-19
首先,用split()方法把英文句子拆分成单词数组,然后把这些单词放入Map中统计:
String str="I am a student,I am thirteen-years old.";
String[] words=str.split(" |,|\\."); //目前只考虑分隔符为空格、逗号、句点的情况
Map<String,Integer> map=new HashMap<String,Integer>();
for(String s:words)
{
if(map.containsKey(s))
{
int i=map.get(s);
map.put(s,i+1);
}
else
{
map.put(s,1);
}
}
System.out.println(map);本回答被网友采纳
相似回答