Kotlinlearncs.online LogoJava
Return to List

Solve: LongToShort

Created By: Rohith Sanjay
/ Version: 2024.9.0

Words are great, but some are just too long. For this problem, write a method called longToShort which takes in one argument (an Array<String>?) finds the longest string in the array, and returns the first n characters, where n is the length of the shortest string in the array. Examples: For example, if the input array is ["We", "love", "CS124"], then your method should return "CS" because "CS124" is the longest string and 2 is the length of the shortest string ("We"), so you return the first 2 characters of "CS124", which is "CS". Second Example: If the input array is ["Java", "and", "Kotlin"], then return "Kot". If the input array contains an empty string, return the empty string. Note: You may assume that the shortest and longest words are the only words of their length. So there will not be a 'tie' for the shortest and longest words. Also, the longest word is always longer than the shortest word, which means the input array will have at least 2 elements. Hint: The .substring() and .length string methods will be useful here. Also, as you loop through the array, you need to keep track of the shortest and longest words. Null case: If the input array is null, return the empty string.

Related Lessons

Stuck? You may find these lessons helpful:

Report a Problem

Attribution must link to this page: https://www.learncs.online/solve/kotlin/longtoshort/[email protected]