CS50 PSET2 Readability练习:JS For Loop单词计数结果少1问题求助
问题原因
通过统计空格数量计算单词数的逻辑下,N个由空格分隔的单词对应N-1个空格,因此最终的空格总数需要加1才能得到正确的单词数。
C语言代码中已经将单词计数器words的初始值设为1,而JavaScript代码中words初始值为0,因此最终输出结果比预期少1。
修正方案
直接将JavaScript代码中的words初始值修改为1即可:
let text = "It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him." // 初始值设为1,对齐统计逻辑 let words = 1; let textArray = Array.from(text); //Words for (let i = 0; i < textArray.length; i++){ if (textArray[i] == " "){ words ++; } } console.log("Words: " + words);
如果需要兼容文本首尾带空格、多连续空格的场景,可以用更稳妥的实现方式:
let text = "It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him." // 先处理空格:去除首尾空格、多个连续空格替换为单个 const processedText = text.trim().replace(/\s+/g, ' ') // 文本为空时单词数为0,否则按空格分割取长度 const words = processedText ? processedText.split(' ').length : 0 console.log("Words: " + words);
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

