Is this counting spaces correctly?

So I wrote:

function findLongestWordLength(str) {
  let letterCount = 0; 
  let highestCount = 0; 
  for(var i=0; i<str.length; i++) {
    if (str[i] == " ") {
      if (letterCount > highestCount) {
        highestCount = letterCount; 
      letterCount = 0;  
  return highestCount;

this is wrong because your space checking if condition need to be if/else. Your current code would increment letterCount no matter what the letter is, which would make every word length counted after the first one 1 character too long.

That fixed it for all except this test:

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")

We’d need to see your most recent code in order to help you. We don’t know exactly what you changed.

Also, I would suggest that this might be easier to solve if you used one of JS’s built in methods for strings. Do you recall a method that might make it real easy to split a sentence into words?

1 Like

Think about your code, what would happen if the last word of the test string is the longest? At which point does that words letter count become your highest count?

The clue is in what your code outputs with the test string "What if we try a super-long word such as otorhinolaryngology". Your code outputs 10 which is the length of super-long. Why is that?

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