简体   繁体   中英

Why doesn't the second code work the same as the first code?

The First Code works correctly and displays the right answer which is 19.

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

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

The second code below, only works until the word "super-long" and logs 10 as the final output, which is incorrect. I'm trying to figure out what goes wrong here. It works fine with other sentences,

FOR REFERENCE

The str.length in the sentence is 60(spaces included), and there are 9 spaces in between the entire sentence


function findLongestWordLength(str) {
  let high = 0;
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] != " ") {
      count++;
    } else {
      if (count >= high)
        high = count;
      count = 0;
    }
  }
  return high;
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

count could be holding a non-zero value at the end of the loop, which will get ignored. Just add a check at the end of the loop as well to update that value.

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

In order to get 19, you have to end your string with a space. Because the last character of "otorhinolaryngology" is a 'y' , you simply increment count at the very end and you never hit your else condition which will update high. Put a space at the end, add an extra condition checking if i == str.length -1 Or simply use the length algorithm, or, as I would prefer, use a reducer like so:

const findLongestWordLength = str => str.split(' ').reduce((acc, word) => word.length > acc ? word.length : acc, 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM