Peter Utekal
Peter Utekal

Reputation: 125

Finding the longest word in a string is not working

I'm supposed to find the longest word in a string, this is the code I've come up with so far. Unfortunately, this seems not to be working, and my question is why?

function findLongestWordLength(str) { 
  str.split("");
  let longest = 1;
  for(let i = 0; i < str.length; i++){
    if (str[i].length > longest){
       longest = str[i].length;
    }
  }
  return longest;
}

Upvotes: 1

Views: 121

Answers (7)

UncleFifi
UncleFifi

Reputation: 895

function spacer(m)
{
  var space = "";
  for(var inst = 0; inst < m;inst++)
    space += "\n";
  console.log(space);
}

function findLongestWordLength(str) {

  //Checking that what you are sending is a string...
  if(typeof str !== "string")
    throw "This function requires you to pass in a string...";

  //Ghetto Class...lol
  function CreateWord(word)
  {
      this.word = word;
      this.length = word.length;
  }

  // Getting all the words...but taking out the words that are ""
  var AllWords = str.split(" ").filter(word => word != ""),

    // This is how many words you have that are not ""
    wordCount = AllWords.length,

    // Defaulting the longest word to the first word...
    longest = new CreateWord(AllWords[0]);

    // if we only have one, we return the one word...
    if(wordCount === 1)
        return longest;

  for(let i = 0; i < wordCount; i++){
    if (AllWords[i].length > longest.length){
       longest = new CreateWord(AllWords[i]);
    }
  }
  return longest;
}

//Simple Test...
var Implementation = findLongestWordLength("ONE TWO THREE FOUR  TESTINGLONGWORD");
console.log(Implementation);
console.log(`Word: ${Implementation.word}`);
console.log(`Length: ${Implementation.length}`);

spacer(3);

//Single word...
var Implementation2 = findLongestWordLength("Only-One-Word");
console.log(Implementation2);
console.log(`Word: ${Implementation2.word}`);
console.log(`Length: ${Implementation2.length}`);

spacer(3);

//Exception...because I dont want want you to misUse this function....
var Implementation3 = findLongestWordLength(null);
console.log(Implementation3);
console.log(`Word: ${Implementation3.word}`);
console.log(`Length: ${Implementation3.length}`);

Upvotes: 0

Shidersz
Shidersz

Reputation: 17190

If I undestood correctly, there are two main issues:

1) You are not storing the result of String.split() anywhere.

2) If you need to split the distinct words, you will need to split by space

I will also start with longest = 0 instead of 1

Example:

function findLongestWordLength(str)
{ 
    str = str.split(" ");
    let longest = 0;

    for (let i = 0; i < str.length; i++)
    {
        if (str[i].length > longest)
            longest = str[i].length;
    }

    return longest;
}

console.log(findLongestWordLength("Hello World"));
console.log(findLongestWordLength(""));
console.log(findLongestWordLength("123 1234567 12345"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Alternatively, you can use Array.map() to map every word to his length, and then spread this array of lengths on Math.max() to get the desired result:

function findLongestWordLength(str)
{
    let wordLengths = str.split(" ").map(word => word.length);
    return Math.max(...wordLengths);
}

console.log(findLongestWordLength("Hello World"));
console.log(findLongestWordLength(""));
console.log(findLongestWordLength("123 1234567 12345"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 3

Supratim Samantray
Supratim Samantray

Reputation: 136

This will not work because you are traversing through each character in the string whose length is 1. You are not comparing the length of the words.

function findLongestWordLength(str) {
    let words = str.split(" ");  // Delemiter to separate words from sentence is space
    let longest = 1;
    for(let i = 0; i < words.length; i++){
    if (words[i].length > longest){
       longest = words[i].length;
    }
  }
  return longest;
}

Upvotes: 0

teimurjan
teimurjan

Reputation: 1975

You need to split the string by " ". Then iterate through the words and return the biggest one's length.

function findLongestWordLength(str) {
  const words = str.split(" ");
  return words.reduce(
    (max, word) => (word.length > max ? word.length : max),
    0
  );
}

console.log(findLongestWordLength("hello world"));

This solution is shorter and cleaner because of using reduce.

Upvotes: 1

user4144271
user4144271

Reputation:

function findLongestWordLength(str) { 
  var otherStr = str.split(" ");
  let longest = 0;
  for(let i = 1; i < otherStr.length; i++){
    if (otherStr[i].length > otherStr[longest].length){
       longest = i;
    }
  }
  return otherStr[longest];
}

findLongestWordLength("This is the String Data")

Upvotes: 0

Tanmay Patel
Tanmay Patel

Reputation: 1810

You can try this code.

function findLongestWordLength(str) {
  var strSplit = str.split(' ');
  var longest = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longest){
    longest = strSplit[i].length;
     }
  }
  return longest;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

The problem is second line need change to str = str.split(" "); because Strings are immutable they cannot change, need reassign it.

function findLongestWordLength(str) { 
  str = str.split(" ");
  let longest = 1;
  console.log(str);
  for(let i = 0; i < str.length; i++){
    if (str[i].length > longest){
       longest = str[i].length;
    }
  }
  return longest;
}

var result = findLongestWordLength("Joan Ala Valeron")
console.log(result);

Upvotes: 1

Related Questions