JavaScript-将字符串拆分为单词,识别元音最多的单词的函数-使用For循环

时间:2019-03-22 23:17:17

标签: javascript for-loop split

我已经检查了一些similar questions,但我不认为答案直接适用于我要寻找的内容。

我试图在给定的字符串中找到元音最多的单词。我知道如何将字符串拆分成这样的单词:

let words = string.split(" ");

到目前为止,我有:

function mostVowels(string) {

  let vowels = ["aeiouAEIOU"];
  let words = string.split(" ");

  //initiate vowel count at 0

  let counter = 0;

  //loop through words

  for (let i = 0; i < words.length; i++) {
    //if there are vowels in the word, add vowels to counter
    if (vowels.includes(i)) {
      counter++
    }
  }
  return counter;
}

console.log(mostVowels("I went to the park today."));

因此,显然我距离解决方案还很远。

现在,这将返回0

该字符串的前五个单词中的每个都有一个元音,而“ today”中有两个元音,因此最终我们希望此函数将“ today”作为元音最多的单词返回。

这时,我只是想获取字符串中第一个单词的元音计数-应该为1

然后我认为我可以比较不同单词的计数以确定哪个计数最大。

4 个答案:

答案 0 :(得分:2)

vowels定义为字符的数组,而不是包含单个字符串的数组。然后,在words上的循环内,将计数器初始化为0,并遍历单词中的每个 character 。如果字符包含在元音数组中,请增加计数器。在对该单词进行迭代结束时,如果该单词的计数器比到目前为止的最佳计数器更好,则将计数器和该单词分配给外部变量,以指示到目前为止的最佳单词/计数器。在函数末尾,返回最佳单词:

function mostVowels(string) {

  let vowels = [..."aeiouAEIOU"];
  let words = string.split(" ");

  let bestCounter = 0;
  let bestWord;
  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    //initiate vowel count at 0
    let counter = 0;
    for (let i = 0; i < word.length; i++) {
      const char = word[i];
      //if there are vowels in the word, add vowels to counter
      if (vowels.includes(char)) {
        counter++
      }
    }
    // finished iterating through loop,
    // now check to see if it's better than the best word so far:
    if (counter > bestCounter) {
      bestCounter = counter;
      bestWord = word;
    }
  }
  return bestWord;
}

console.log(mostVowels("I went to the park today."));
console.log(mostVowels("I went to the fooaeuiubar park today."));

或者,也许更优雅地使用数组方法:

const vowels = [..."aeiouAEIOU"];
const getVowelCount = word => [...word].reduce((a, char) => a + Boolean(vowels.includes(char)), 0);
function mostVowels(string) {
  let bestCounter = 0;
  return string.split(' ')
    .reduce((bestWordSoFar, thisWord) => {
      const thisVowelCount = getVowelCount(thisWord);
      if (thisVowelCount > bestCounter) {
        bestCounter = thisVowelCount;
        return thisWord;
      } else {
        return bestWordSoFar;
      }
    });
}

console.log(mostVowels("I went to the park today."));
console.log(mostVowels("I went to the fooaeuiubar park today."));

答案 1 :(得分:1)

我试图通过map-reduce来解决这个问题,以保持事物的纯净和干净。但是我不得不将mostVowels设置为reduce,使其显得有些愚蠢。

但这是我的镜头:

const handleSentence = (sentence = '') => {
  const vowels = /[a|e|i|o|u]+/gi;
  const words = sentence.split(' ');
  let mostVowels = '';
  
  const getVowels = (str = '') => {
    try {
      return str.match(vowels).join('').length
    } catch (err) {
      return 0;
    }
  };

  const getMostVowels = (a, b, i) => {
    if (a < b) {
      mostVowels = words[i];
      return b;
    }
  
    return a;
  }
  
  words.map(getVowels).reduce(getMostVowels);
  return mostVowels;
}

console.log(handleSentence('this is an example string for demonstrating the function'));

console.log(handleSentence('yet another example of the effectiveness of function'));

console.log(handleSentence('gypsy rhythm'));

答案 2 :(得分:1)

另一种方法是使用regex

let mostVowels = (input) =>{
  let max = 0;
  let splited = input.split(' ')
  splited.forEach((e, index) => {
    let count = (e.match(/[aeiou]/gi)||[]).length
    max = count > max ? index : max
  })
  return splited[max]
}

console.log(mostVowels("I went to the park today."));
console.log(mostVowels("I went to the fooaeuiubar park today. xyz"));

答案 3 :(得分:1)

排序更短:

const vowels = s => s.split(/[aeiou]/i).length - 1; 

const mostVowels = s => s.split(/\W/).sort((a, b) => vowels(b) - vowels(a))[0];

console.log( mostVowels("I went to the park today.") );

且未排序:

const vowels = s => s.replace(/[^aeiou]/gi, '').length;

const mostVowels = s => s.split(/\W/).reduce((a, b) => vowels(a) > vowels(b) ? a : b);

console.log( mostVowels("I went to the park today.") );