使用charAt,IndexOf计算字符串中每个单词的长度

时间:2014-07-29 16:15:10

标签: java

我正在寻找一种方法来创建一个在while循环中使用初始状态的方法,它将使用charAt,IndexOf计算字符串中每个单词的长度。 我希望输出符合以下几点:

  

你好世界你好吗

There are 0 words of length 0 
There are 0 words of length 1 
There are 0 words of length 2 
There are 3 words of length 3 
There are 0 words of length 4 
There are 2 words of length 5

2 个答案:

答案 0 :(得分:0)

int count(String s, int len){
            int result=0;
            StringTokenizer st=new StringTokenizer(s,"[ ,;]");
            while(st.hasMoreTokens()){
                if(st.nextToken().length()==len){
                    result++;
                }
            }
            return result;
        }

 void loopMethod(){
            String s="Hello world how are you";
            for(int i=0;i<=5;i++){
                System.out.println("There are "+count(s,i)+" words of lenghth "+i);
            }
        }

答案 1 :(得分:0)

void run(){
            String s="Hello world how are you";
            Map<Integer, Integer> result=new TreeMap<>();

            StringTokenizer st=new StringTokenizer(s,"[ ,;]");//[ ,;]-regex
                while(st.hasMoreTokens()){
                    int lenght=st.nextToken().length();
                    if(!result.containsKey(lenght)){
                        result.put(lenght, 1);
                }
                    else{
                        result.put(lenght, result.get(lenght)+1);
                    }


        }       /*//display only if you have 1 or more words of that length
                for(Map.Entry<Integer, Integer> e:result.entrySet()){ 
                    System.out.println("There are "+e.getValue()+" words of length "+e.getKey());
                }
}

这是一个更复杂的变体,使用TreeMap(一个对键进行排序的HashMap)创建。此外,您可以使用Pattern和Matcher类来解析String。它们更有效率。