Find the Longest Word in a String (without using the split method)

Find the Longest Word in a String (without using the split method)
0

Please dont judge me I’m a newbie, but I have a question about how approach this problem . I’m wondering how to solve this without using the str.split method. The reason why I’m asking is because when I clicked on the Get a hint button it immediately tells me to split a string into an array of words , but after looking back at some of the challenges I have not really been taught how to do that.

so far I have pushed the string into an array but I have no way of splitting off each individual word to find its individual length.

my thought process so far is :

  1. put the string into an array (done )

  2. separate each word (without using str.split)

  3. find the length of each word ( using the .length method)

  4. store and compare each length of the string ( still trying to think of ways to do that )

I know that there is basically no code for ya’ll to review and comment on but I’m having a really hard time approaching this. I already solved the problem by copy pasting but I hate myself for doing that and it didnt help me understand anything.

Your code so far


function findLongestWordLength(str) {
    let words = []
   
    words.push(str);



    console.log(words)


  
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");


Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 11316.148.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.117 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

First of all. Why do you think you need an array at all?

You could just use two “tracking” variables. One to keep track of the current word and one to keep track of the longest word seen so far.

I will let you think about the initial values of what these should be.

Next, it is just a matter of iterating through each character of str (strings are iterable just like arrays) to “build” a word. When you come across a space character or then end of str you know you have a complete word. You compare the length of this word with the current longest word (your other tracking variable) and assign the larger of the two to your longest word tracking variable. At the very end of the iteration your longest word tracking variable will contain the longest word length which you can return.

Note: You will need to reset the word variable after you check it’s length, so it does not continue “building” through the rest of the iteration.

ok so after taking your advice my current code looks like this:

function findLongestWordLength(str) {
  var longestWord = "";  // what do I initialize this with?
  var currentWord = "";

  // unsure about the use of str.length for this loop 
  for (var i = 0; i < str.length; i++) {
// iterate through the strings individual characters and spaces to "build a word" (is this right?) 
}
// set the "built" word to the current word (I use psuedocode here) 
currentWord = "built" word 

// comparing the built words (I use psuedocode here}
if (the current word is the longest){
the longest word will be equal to the  built word 
}
else if (
the new built word is longer than the current word
 ){ set the longest word equal to the newly built word}


I honestly feel stupid for not really figuring it out after you’ve given me such a big hint , I’m also definitely unsure if I’m going in the right direction ( currently looking through the regex problems and loops problems to see if I can “build” a word ) .

where should I go from here?

Think back to the Concatenating Strings with the Plus Equals Operator challenge for how you could build word.

You can simplify your logic by only changing the value of the longest word based on the condition you have in your else if statement. Doing this would allow you to use a single if statement.

What type of value will longestWord need to be? String, Number, Object, Array, etc…

This is very frustrating , I’m still having huge issues. so now I’ve initialized the two variables with quotes “” but my for loop isnt working and I dont know why.

Think back to the Concatenating Strings with the Plus Equals Operator challenge for how you could build word.

so I looked at that and solved the problem but what was I supposed to get out of it? my loop doesnt seem to want to build the string. when I try to get it to print out a word it prints out a single letter

function findLongestWordLength(str) {
  let currentWord = ""
  let longestWord = ""

  for (let i = 0 ; i <str.length; i++){
    return currentWord += str[i];
  }
if (currentWord.length > longestWord.length) longestWord = currentWord; 
    } else {
      currentWord="" ;
    }
  }
  if (currentWord > longestWord) longestWord = currentWord; 
  return longestWord;
}
  
  
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

I am I just not smart enough to put all of these lessons together ? should I just give up on being a programmer ? it seems like I just cant grasp fundamental concepts to do something very simple even with major hints.

Remember, the return statement causes the function to exit and return a value, so you don’t want to use it in your for loop.

You will be fine. It just takes practice. Just because I gave you some hints/advice, does not necessarily mean they were “major” hints or “easy” to implement. I just gave you some structure to work with if you wanted to solve the challenge without using the split method. Many of the methods shown in the Guide solutions and later you learn about in the Functional Programming section do a lot of the hard work for you, but I think it is important to solve these challenges without using these methods, because it forces you to think about all the moving parts. Obviously, you don’t want to reinvent the wheel every time you solve a problem, so once you learn a “shortcut”, you would definitely use it from then on.

You seem to be missing an opening curly bracket { after the (.

1 Like

Please don’t put yourself down. You are doing fine.

I was sure that this was going to work :

function findLongestWordLength(str) {
  let currentWord = ""
  let longestWord = ""

  for (let i = 0 ; i <str.length; i++){
    if(str[i] === " "){
      if (currentWord.length > longestWord.length) longestWord = currentWord; 
      currentWord ="";
    } 
    else {
     currentWord += str[i];
  }
  }

  
  return longestWord.length;
}

for some reason it satisfies everything but the last requirement ( I asked someone what you meant by the concatenation and the showed me the currentWord += str[i] which made me feel extra dumb for something so simple) I figured out the str[i] === " " on my own which felt good but what am I missing?

Maybe I don’t understand fully, but why are you returning longestWord.length instead of just the word?

its part of this challenge problem :

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string

It may be that in the last test the longest word is at the end of the string? You are missing that, because in that case the if statement doesn’t execute as it is checking for a space - you can do it in two ways here, change the string before looping over it, or change something in your loop

1 Like
@Quantumike this is solution which you was looking for
function findLongestWordLength(str) 
{

var tempString= "";
var newArray=[];

  for(let i=0;i<str.length;i++)
  {
      
      if(str[i]!==" ")
      {
        tempString+=str[i];
      }
      else
      {
        newArray.push(tempString);
        tempString="";
      }
  }
// newArray is new array ;
  let maxLength=0;
      for(let i=0;i<newArray.length;i++)
      {
        if(newArray[i].length>maxLength)
        {
          maxLength=newArray[i].length;
        }
      }
        return maxLength;

  }

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));