Kotlinlearncs.online LogoJava
Return to List

Solve: Small Word Filter With Array

Created By: Geoffrey Challen
/ Version: 2021.9.0

Write a method called smallWordFilter that, given a String containing words separated by single spaces (" "), returns all the words in the original String that are 3 characters or shorter in the same order in which they appeared in the original String, as an Array<String>.

For example, given the input "Xyz is the very best cat" you would return the Array<String> {"Xyz", "is", "the", "cat"}. We have skipped both "very" and "best" because they are longer than 3 characters.

This is a problem that would be much easier to solve using a list, since you don't know exactly how many part of the input String are 3 characters or smaller! But this can be done with an array, if somewhat awkwardly. Here's a solution sketch to help you get started:

  1. Split the array based on the single space " "
  2. Next, count the number of parts of the String that are 3 characters or smaller
  3. Now create your Array<String> of the appropriate size, initialized with empty Strings
  4. And then loop again through the array of String parts filling your output array as you go

We've provided some starter code to help you get going on this problem.

fun smallWordFilter(words: String): Array<String> {
val parts = words.split(" ")
var count = 0
// count words that meet the criteria
val toReturn = Array(count) { "" }
// now populate the toReturn array
return toReturn
}

Related Lessons

Stuck? You may find these lessons helpful: