P
P
Pioneer022022-04-20 15:28:55
Java
Pioneer02, 2022-04-20 15:28:55

How to display the number of words of the same length in a string?

output the number of words of the same length from the string. For example: String[aaf ff aaa bb] , and it contains 2 words - length 3 and 2 words - length 2. I tried, but it turns out crooked and wrong. Methods cannot be used

public static int CountLength(String str){
String word1 = str.substring(0,3);
Stringword2 = str.substring(4,6);
Stringword3 = str.substring(7,10);
Stringword4 = str.substring(11,13);
int count=0;
if(word1.length() == word2.length()) count++;
else count--;
if(word1.length() == word3.length()) count++;
else count--;
if(word1.length() == word4.length()) count++;
else count--;
if(word2.length() == word3.length()) count++;
else count--;
if(word2.length() == word4.length()) count++;
else count--;
if(word3.length() == word4.length()) count++;
else count--;
return count;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TurboKaban, 2022-04-20
@TurboKaban

try splitting the string into an array, then into a hashmap, in which the key is the length of the word, and value is the counter. Only I didn’t understand the condition of the problem, so in my example from the map I print the length of the word and the number of words of this length

String myStr = "aaa as dsr asf 33";
        String s[] = myStr.split(" ");
        Map<Integer, Integer> map = new HashMap();
        for (int i = 0; i < s.length; i++) {
            int l = s[i].length();
            map.put(l, map.containsKey(l) ? map.get(l) + 1 : 1 );
        }
        map.forEach((k, v) -> System.out.println( k + ": " + v));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question