所以我写了一个代码,可以检测句子中的所有单词.我只会检测单词并忽略空白,这意味着即使字符串中有空位,我也不会对它们进行计数.但结果并不是我想象的.代码如下:

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.但我得到了奇怪的输出.请帮

推荐答案

您有几个错误:

  1. 第一次使用变量后不要使用var
  2. When the element isn't a space, check whether it's
    a. a first element in a string (indexcount === 0)
    b. or the previous character is a space (mystring[index - 1] === ' ')
    If so increase the word count

var mystring = "Hello World"
var indexcount = 0
var words = 0

for (var element of mystring) {
  if (element !== " " && (indexcount === 0 || mystring[indexcount - 1] === " ")) {
    words = words + 1;
  }
  indexcount = indexcount + 1;
}

console.log(words);

考虑使用状态机:

var mystring = ` Hello 
                 World `;

const spaces = new Set('\t\r\n '.split('')); // detect spaces with a set
let words = 0;
let inWord = false; //whether we are inside of a word or not

for(const char of mystring){
  if(spaces.has(char)){
    inWord = false;
  } else if(!inWord) {
    words++; 
    inWord = true;
  }
}
   
console.log(words);

您还可以使用regex:

var mystring = ` Hello 
                 World `;

const words = mystring.match(/(?<=\s|^)(?=\S)/g).length;
   
console.log(words);

Javascript相关问答推荐

Python类实现的JavaScript吊坠是什么样子的?

如何在非独立组件中使用独立组件?

如何使用CSS和JavaScript创建粘性、凝聚力的形状到形状(容器)变形?

如何避免使用ajax在Vue 3合成API中重定向

如何在加载的元数据上使用juserc和await中获得同步负载?

Vue Quill css仅应用于我的第一个Quill Editor组件+如何自定义工具栏

如何通过在提交时工作的函数显示dom元素?

我应该绑定不影响状态的函数吗?'

康威的生活游戏规则在我的Javascript版本中不起作用.''我做错了什么?

Promise Chain中的第二个useState不更新

这个值总是返回未定义的-Reaction

JS:XML insertBefore插入元素

正则表达式,允许我匹配除已定义的子字符串之外的所有内容

400 bad request error posting through node-fetch

删除加载页面时不存在的元素(JavaScript)

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

处理TypeScrip Vue组件未初始化的react 对象

如何根据输入数量正确显示alert ?

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

React Refs不与高阶组件(HOC)中的动态生成组件一起工作