gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:31:45 25 4
gpt4 key购买 nike

我检查了一些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

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

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

然后我想我将能够比较不同单词的计数以确定哪个计数最大。

最佳答案

元音定义为字符数组,而不是包含单个字符串的数组。然后,在 words 循环内,将计数器初始化为 0,并迭代单词中的每个字符。如果该字符包含在元音数组中,则递增计数器。在迭代单词结束时,如果该单词的计数器优于迄今为止最好的计数器,则将计数器和单词分配给外部变量,指示迄今为止最好的单词/计数器。在函数结束时,返回最好的单词:

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."));

关于JavaScript - 将字符串拆分为单词、识别元音最多的单词的函数 - 使用 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com