Java如何计算文件中每个单词的首字母

时间:2014-05-25 14:47:07

标签: java

基本上标题是什么。我在做这件事时遇到了很多麻烦。 有没有一种简单的方法来使用charAt?到目前为止我已经尝试了这个

while (scanner.hasNextLine())
        {
            StringTokenizer st = new StringTokenizer(theText, " /n");    

            String word = st.nextToken();

            char firstChar = word.charAt(0);

            if(theText.charAt(0) == 'a')
            {
                a++;
            }

2 个答案:

答案 0 :(得分:0)

为此目的使用地图。

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

public class StudentBean {
    public static void main(String[] args) throws Exception {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        String thisLine = null;
        try {
            // open input stream test.txt for reading purpose.
            BufferedReader br = new BufferedReader(new FileReader("c:/test.txt"));
            while ((thisLine = br.readLine()) != null) {
                String[] wordsArray = thisLine.split(" ");
                for (String word : wordsArray) {
                    char firstChar = word.charAt(0);
                    // if map contains that character, increase counter
                    if (map.containsKey(firstChar)) {
                        map.put(firstChar, map.get(firstChar) + 1);
                    }
                    // if map does not contain that character, add that
                    // character with counter = 1
                    else {
                        map.put(firstChar, 1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

扫描仪会为您分割单词,因此无需按照某些注释中的建议拆分字符串。你可以简单地写

    Map<Character, Integer> charCount = new HashMap<Character, Integer>();        
    Scanner scanner = new Scanner("This is a sentence.");

    while (scanner.hasNext()) {
        char firstChar = scanner.next().charAt(0);

        if (charCount.containsKey(firstChar)) {
            charCount.put(firstChar, charCount.get(firstChar) + 1);
        }
        else {
            charCount.put(firstChar, 1);
        }
    }

    // Print out each of the values.
    for (Entry<Character, Integer> entry: charCount.entrySet()) {
        char character = entry.getKey();
        int count = entry.getValue();
        System.out.println(character + ": " + count);
    }

请注意,这将分别计算大写字母和小写字母。如果您想将它们统计为相同,则应更改

        char firstChar = scanner.next().charAt(0);

        char firstChar = scanner.next().toUpperCase().charAt(0);