计算字符串中的单词

2022-08-30 04:44:51

我试图以这种方式计算文本中的单词:

function WordCount(str) {
  var totalSoFar = 0;
  for (var i = 0; i < WordCount.length; i++)
    if (str(i) === " ") { // if a space is found in str
      totalSoFar = +1; // add 1 to total so far
  }
  totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words
}

console.log(WordCount("Random String"));

我认为我已经很好地理解了这一点,除了我认为这种说法是错误的。检查是否包含空格并添加 1 的部分。ifstr(i)

编辑:

我发现(感谢Blender)我可以用更少的代码做到这一点:

function WordCount(str) { 
  return str.split(" ").length;
}

console.log(WordCount("hello world"));

答案 1

使用方括号,而不是括号:

str[i] === " "

或:charAt

str.charAt(i) === " "

您也可以使用以下命令进行操作:.split()

return str.split(' ').length;

答案 2

在重新发明轮子之前尝试这些

使用 JavaScript 计算字符串中的单词数

function countWords(str) {
  return str.trim().split(/\s+/).length;
}

http://www.mediacollege.com/internet/javascript/text/count-words.html 相比

function countWords(s){
    s = s.replace(/(^\s*)|(\s*$)/gi,"");//exclude  start and end white-space
    s = s.replace(/[ ]{2,}/gi," ");//2 or more space to 1
    s = s.replace(/\n /,"\n"); // exclude newline with a start spacing
    return s.split(' ').filter(function(str){return str!="";}).length;
    //return s.split(' ').filter(String).length; - this can also be used
}

使用JavaScript来计算字符串中的单词,而不使用正则表达式 - 这将是最好的方法

function WordCount(str) {
     return str.split(' ')
            .filter(function(n) { return n != '' })
            .length;
}

作者笔记:

您可以调整此脚本以您喜欢的任何方式计算单词。重要的部分是 - 这计算空间。该脚本尝试在计数之前删除所有多余的空格(双倍空格等)。如果文本包含两个单词,它们之间没有空格,则会将它们计为一个单词,例如“第一句。下一句的开头”。s.split(' ').length