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

Java 使用charAt、IndexOf计算字符串中每个单词的长度,java,Java,我正在寻找一种在while循环中创建初始状态的方法,该方法将使用charAt、IndexOf计算字符串中每个单词的长度。 我希望输出符合以下内容: 你好,世界,你好吗 int计数(字符串s,int len){ int结果=0; StringTokenizer st=新的StringTokenizer,“[,;]”; 而(st.hasMoreTokens()){ 如果(st.nextToken().length()==len){ 结果++; } } 返回结果; } void loopMethod(

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

你好,世界,你好吗

int计数(字符串s,int len){
int结果=0;
StringTokenizer st=新的StringTokenizer,“[,;]”;
而(st.hasMoreTokens()){
如果(st.nextToken().length()==len){
结果++;
}
}
返回结果;
}
void loopMethod(){
String s=“你好,世界你好”;
对于(int i=0;i
void run(){
String s=“你好,世界你好”;
映射结果=新树映射();
StringTokenizer st=新的StringTokenizer,“[,;]”;//[,;]-regex
而(st.hasMoreTokens()){
int lenght=st.nextToken().length();
如果(!result.containsKey(长度)){
结果。放置(长度,1);
}
否则{
结果.put(长度,结果.get(长度)+1);
}
}//*//仅当有一个或多个该长度的单词时显示
对于(Map.Entry e:result.entrySet()){
System.out.println(“有”+e.getValue()+“长度为”+e.getKey())的单词);
}
}

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

您愿意使用
String.length()吗
?您可以拆分字符串,获取各个片段的长度,并将其存储到哈希映射中。您可以使用该映射吗?或者您对不使用该映射有限制吗?是的,我愿意使用string.length(),并且没有设置限制,但还没有使用哈希映射,也没有使用java long。
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
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);
            }
        }
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());
                }
}