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
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