2014恒生电子笔试题

来源:互联网 发布:sftp传输需要哪些端口 编辑:程序博客网 时间:2024/04/28 06:01

题目:有一篇英文文章保存在scr.txt中,求出这篇文章中所有的英文单词,且每个单词出现的次数,最后在控制台打印输出。

解题思路:首先要将文章从src.txt中读出,然后将取出的英文文章保存在字符串中。然后根据所得的字符串做处理,循环取出单词,对于这些单词采用map的形式存入,以单词为键值,以出现的次数为value,判断单词是否存在map中,可以采用map中的containsKey方法,对于已存在的只需替换单词的value,反之则新加一个。最后通过Set<Map.Entry<String, Integer>> sets = map.entrySet();获得map集合,最后获得map中的所有元素。


代码如下:

package com.suur.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CountWord {

    public static void main(String args[]) throws IOException{
        File file = new File("E:/a.txt");
        FileInputStream fis = new FileInputStream(file);
        int len = 0;
        byte buf[] = new byte[1024];
        String str ="";
        String temp="";
        Map<String,Integer> map = new HashMap<String,Integer>();
        while((len=fis.read(buf))!=-1){
            str += new String(buf,0,len);
        }
        
        for(int i=0;i<str.length();i++){
            char c = str.charAt(i);
            if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){
                temp+=c;
            }else{
                if(map!=null){
                    if(map.containsKey(temp)){
                        Integer integer = map.get(temp);
                        map.replace(temp, integer+1);
                    }else{
                        map.put(temp, 1);
                    }
                }else{
                    map.put(temp, 1);
                }
                temp="";
            }
        }
        Set<Map.Entry<String, Integer>> sets = map.entrySet();
        for(Map.Entry<String, Integer> s:sets){
            if((s.getKey()!=null)&&(!"".equals(s.getKey())))
                System.out.println("单词:"+s.getKey()+"出现次数:"+s.getValue());
        }
    }
}


0 0
原创粉丝点击