Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
My code is giving different outputs. please check my code.

``````console.log("largest word "+findLongestWordLength("Hello"));
console.log("largest word "+findLongestWordLength("Hello "));
``````
``````Output:

largest word 1
largest word 5
``````
``````function findLongestWordLength(str) {
let count=0;

for(let i=0;i<str.length;i++){

if(str[i]!=" "){
count +=1;
}
else{
result= result<count?result=count:result=result;

count=0;
}
}
return result;
}

let result=1;

console.log("largest word "+findLongestWordLength("Hello"));
console.log("largest word "+findLongestWordLength("Hello "));

// The quick brown fox jumped over the lazy dog
``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36`

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Helloo

So you are accumulating count for ‘Hello’, lets say… and then what? Your function returns something called result

Your logic deals fine with situations when after word we have a space.

What if after word it is finish? End of the whole string?

function returns largest word in a string.
e.g. `hello` should return `5` and `Google do a barrel roll` should return `6`

Yeah, I get it, I know this challenge.

But take a look at your tests

You have issue when word doesn’t end with space (1st case)right?
For second case your function gets the job done

yes. that is the issue, it does not work in first case.

Yep, because your code doesn’t hold this condition(when word ends not with space, but because string ends), you need to add some code to solve this issue.

Or use different approach(string to array conversion), but it’s all up to you of course

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.