所以我编写了一个代码来检测句子中的所有单词。我只会检测单词并忽略空格,这意味着即使字符串中有空格我也不会计算它们。但结果并不是我所期望的。这是代码:
var mystring = "Hello World"
var indexcount = 0
var words = 0
for (element of mystring){
if(element == " " || element[indexcount + 1] != " " || element[indexcount -1] != " "){
var words = words + 1
var indexcount = indexcount + 1
}
else{
indexcount = indexcount + 1
}
}
console.log(words);
因此,这段代码实际上可以帮助任何想要了解字符串中所有单词、忽略所有空格的人。因此,即使字符串中只有一个单词并且仍然有很多空格,结果也会是 1。但是我得到了奇怪的输出。请帮忙
这是您可以尝试的解决方案
function countWords(str) {
// Split the string into an array of words using the split() method
const words = str.split(" ");
// Filter out empty strings (extra spaces) using filter()
const filteredWords = words.filter(word => word.trim() !== "");
// Return the length of the filtered array (number of words)
return filteredWords.length;
}
// Example usage
const myString = "Hello ";
const wordCount = countWords(myString);
console.log("Number of words:", wordCount); // Output: Number of words: 1