Java统计有多少个以某字母开头的单词数目

import java.util.Scanner;

/**
 * 给出一句英文句子统计有多少个以某字母开头的单词
 * @author 佳哥
 *
 */

public class TestChar {
	public static void main(String[] args) {
		char words;
		String str;
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入字符串:");
		str = sc.nextLine();
		System.out.println("请输入开头的字母:");
		words = sc.next().charAt(0);
		System.out.println(str);
		int count = 0;
		String[] strArray = str.split(" ");//把字符串通过" "(空格)拆分为字符串数组
		for (int i = 0; i < strArray.length; i++) {
			
			if(strArray[i].charAt(0) == words)   
			{
				count++;
			}
			
		}
		System.out.println(count);

	}

}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的HashMap来实现。 首先,读取文本文件单词,并将单词的首字母作为HashMap的键,值则为出现的次数。每读取一个单词,判断其首字母是否在HashMap已经存在,如果存在则将该键对应的值加1,否则新建一个键值对。 最后,统计完成后遍历HashMap,输出每个字母开头单词数量。 以下是示例代码: ```java import java.util.*; import java.io.*; public class WordCounter { public static void main(String[] args) throws IOException { // 读取文本文件 BufferedReader reader = new BufferedReader(new FileReader("words.txt")); // 创建HashMap Map<Character, Integer> counterMap = new HashMap<>(); // 逐行读取单词 String line; while ((line = reader.readLine()) != null) { // 获取单词字母 char firstChar = line.charAt(0); // 判断首字母是否在HashMap已经存在 if (counterMap.containsKey(firstChar)) { // 如果存在,则将该键对应的值加1 counterMap.put(firstChar, counterMap.get(firstChar) + 1); } else { // 如果不存在,则新建一个键值对 counterMap.put(firstChar, 1); } } // 关闭文件流 reader.close(); // 输出每个字母开头单词数量 for (Map.Entry<Character, Integer> entry : counterMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } ``` 注意,以上代码使用了try-with-resources语句来自动关闭文件流,需要Java 7及以上版本支持。如果是Java 6或更早的版本,可以使用try-catch-finally语句来手动关闭文件流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值