如何计算java中字符串数组中的单词?

时间:2013-02-18 12:17:39

标签: java

我正在学习数组,我想让程序计算单词。鉴于:String myWords = {"soon; hi; also; soon; job; also"}; ,我必须创建像countWrods(myWords);这样的方法 打印结果应为打印字母顺序,单词数和总单词数。 这是我的代码:

public class Words {
    public static  void main(String[] args){    
        String[] myWords = {"soon; hi; also; soon; job; mother; job; also; soon; later"};
        Words myW= new Words();
        myW.countWords();
        System.out.println("\tWords   \tFreq");
    }
    public  static String[] countWords(myWords){
        for (int i=0; i<myWords.length; i++){
        String temp = myWords[i];
        //System.out.println(temp + " ");
        for(int j=i+1; j<myWords.length; j++){
        String temp2= myWords[j];

            System.out.println("No. of unique words: " );
        }
        }
    }
}

接下来我该怎么做?

4 个答案:

答案 0 :(得分:1)

import java.io.*;
import java.util.*;

public class Count_Words_Scan
{
    void main()throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("ENTER A STRING ");
        String str = br.readLine();
        str= str.toLowerCase();
        int c=0;
        Scanner sc = new Scanner(str);
        while(sc.hasNext())
        {
            sc.next();
            c++;
        }
        System.out.println("NO.OF WORDS = "+c);
    }
}

输入:单词计数器
输出:NO.OF WORDS = 3

答案 1 :(得分:0)

我建议您查看splittrimHashSet

答案 2 :(得分:0)

我假设您想要计算字符串中的单词。

字符串"soon hi also soon job mother job also soon later"

 public class Words {

Map<String , Integer> dictionary=new HashMap<String,Integer>();

public static void main(String[] args) {
    String myWords = "soon hi also soon job mother job also soon later";
    Words myW = new Words();
    String[] array=myWords.split("\\s+");
    myW.countWords(array);
    System.out.println(myW.dictionary);
}

private void countWords(String[] myWords) {

    for(String s:myWords){

        if(dictionary.containsKey(s))
            dictionary.put(s, dictionary.get(s)+1);
        else
            dictionary.put(s, 1);
    }
}
}

O/P : {mother=1, later=1, job=2, hi=1, also=2, soon=3}

答案 3 :(得分:0)

首先,您需要拆分String,大概是“;” - 然后你可以把它打成TreeSet来对它进行排序,然后使单词变得无情。添加计数器以计算总字数。您还可以使用TreeMap来计算每个单词的数量,覆盖地图上的put方法以便在您进行时进行汇总...

final String myString = {"soon; hi; also; soon; job; mother; job; also; soon; later"};
final String[] myStrings = myString.split(";");
final Map<String, Integer> myStringMap = new TreeMap<>(){
 @override
 public String put(final String key, final Integer value) {
   if(contains(key)) {
     return put(key, get(key) + 1);
   } else {
     return put(key, 1);
   } 
 }
};
for(final String string : myStrings) {
  myStringMap.put(string.trim(), 1);
}

现在myStringMap.size()是唯一字词的数量,myStringMap.keys()是所有单词中字母顺序排列的Set,如果您想要总数,则只需要将值相加:< / p>

int totalWords = 0;
for(final Integer count : myStringMap.values()) {
  totalWorks += count;
}