java从键盘或文件读取一段英文文字,统计其中单词个数,并输出所有单词(忽略其他字
发布网友
发布时间:2022-05-23 19:21
我来回答
共3个回答
热心网友
时间:2023-11-13 22:37
public void test(){
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.println("请输入字符串...");
String str = sc.next();
char[] arr = str.toCharArray();
java.util.Map<String, Integer> map = new java.util.HashMap<String, Integer>();
for(int i = 0; i < arr.length; i++){
int count = 0;
w:if(((int)arr[i] >= 65 || (int)arr[i] <= 90) && ((int)arr[i] >= 97) || ((int)arr[i] <= 122)){
for(int j = 0; j < arr.length; j++){
if(arr[i] == arr[j]){
++count;
}
}
map.put(arr[i]+"", count);
}
}
java.util.Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
Integer val = map.get(key);
System.out.println(key+"出现了:" + val);
}
System.out.println("输入的字符串为:"+java.util.Arrays.toString(arr));
}
热心网友
时间:2023-11-13 22:38
//试试我的这种方法,使用正则很好解决
String str = "Hello world";
String regex = "(\\w+)";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(str);
int count = 0;
while (matcher.find()){
count ++;
System.out.println(matcher.group(1));
}
System.out.println("单词个数:"+count);
热心网友
时间:2023-11-13 22:38
import java.io.*;
public class Gd {
public static void main (String[] args)throws Exception{
int a=0;
InputStream in=new FileInputStream("E:/hh.txt");
int s;
while((s=in.read())!=-1){
if(s==32){a++;}
System.out.print((char)s);
}
a++;
System.out.println();
System.out.println("一共读了"+a+"单词");
}
}
用io做一个简单的实现,注意不要没写满就换行(32是空格的数值)