Longest Word Coderbyte Solution

2

Have the function LongestWord(sen) take the sen parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Words may also contain numbers, for example, "Hello world123 567".



Examples

 


 
Input: "fun&!! time"

 Output: time




 Input: "I love dogs"

 Output: love




Longest Word Coderbyte Solution in Java

 
  
public class LongestWord {

final String ALPHABET =
"abcdefghijklmnopqrstuvwxyz";

final String ALPHABET_UPPER = ALPHABET
.toUpperCase();

String LongestWord(String sen) {
String[] words = sen.split("\\s");
String longestWord = null;
int longestWordLength = 0;

for (String word : words) {
int wordLength =
getWordLength(word);
if (longestWord == null || wordLength > longestWordLength) {
longestWord = word;
longestWordLength = wordLength;
}
}

return longestWord;
}

int getWordLength(String str) {
int length = 0;

for (char c : str.toCharArray()) {
if (ALPHABET.indexOf(c) > -1 || ALPHABET_UPPER.indexOf(c) > -1) {
length++;
}
}
return length;
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
LongestWord c = new LongestWord();
System.out.print(c.LongestWord(s.nextLine()));
}
}

 
Longest Word Coderbyte Solution in JavaScript


function LongestWord(sen) {
var arr = sen.replace(/[^a-zA-Z ]/g,"").split(" ");
arr.sort(function(a,b) { return b.length - a.length } );
return arr.shift();

}

Explanation

When working on the solution, you have to be aware of the directions that say to ignore punctuation. That means we need to strip out everything in the string except for the letters a-z and space.  Once removed, I am going to use the sort() function for Array to sort each word by the length in descending order. The first entry in the array is the longest word.

Post a Comment

2 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment
Our website uses cookies to enhance your experience. Learn More
Accept !