简体   繁体   中英

Finding longest word in a string javascript code that is not working on the last wordd

I've already solved this by using a split function but I'm still confused as to why my previous for-loop only code is not working when I'm trying to find the longest word in a string in javascript. The function I'm writing is supposed to return the number of letters of the longest word. After using the console, whenever i use only one word, it returns the value i initialized the counter of the letters with (which is 0). If the longest word is the last word, it returns the second longest word on the preceding words. If the longest word is on anywhere except the last word, the result is accurate. It seems like it has trouble counting the letters of the last word. Here is my code.

let lettCount = 0;
let largest = 0;
let spaceCheck = /\s/;
  for (let i = 0; i < str.length; i++) {
    if (spaceCheck.test(str[i]) == true) {
      if (lettCount > largest) {
        largest = lettCount;
      }
      lettCount = 0;
    }
    else {
      lettCount++;
    }
  }
  return largest;

You should be able to simplify the logic here significantly, using String.split() and Math.max() .

We split the string into an array, then use Array.map() to get the length of each word, then use Math.max() along with the Spread syntax to get the longest word.

 let str = 'the longest word is dinosaur'; function getLongest(str) { return Math.max(...str.split(/\\s/).map(s => s.length)); } console.log('Longest word:', getLongest(str));

You can also do this with String.split() and Array.reduce() , this is even a little simpler:

 let str = 'the longest word is dinosaur'; function getLongest(str) { return str.split(/\\s/).reduce((acc,s) => s.length > acc ? s.length: acc, 0); } console.log('Longest word:', getLongest(str));

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