Answer:
The solution code is writing in Python.
- import re
-
- def count_word_lengths(s):
- processed_str = re.sub(' +', ' ', s)
-
- count = 0
- word_list = processed_str.split(" ")
- word_length_list = []
-
- if(len(word_list) == 1):
- return []
- else:
- for x in word_list:
- word_length_list.append(len(x))
-
- return word_length_list
-
-
- print(count_word_lengths("i have a dream"))
Step-by-step explanation:
Since this program is expected to handle multiple consecutive spaces, we need to import Python regular expression module, re (Line 1). The usage of re is to use its sub method to substitute those multiple spaces with single space ' ' and assigned the modified string to variable processed_str (Line 4).
Next, use the string split() method to transform the processed_str into a list of individual words using single space " " as separator and assign the list to variable word_list (Line 7).
If the word_list contains only one word, this means the input string is either empty or no spaces and therefore it return empty list (Line 10). Otherwise, the program will proceed to a for loop that traverse through each word in the word_list and use len() method to get the length of the individual word and add the length value to the word_length_list (Line 13-14). At last, return the word_length_list as output (Line 16).
We can test the function using a sample string as in Line 19 and the output is [1, 4, 1, 5].