计算字符串中的单词 [英] Counting words in string
本文介绍了计算字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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"));
我想我已经很好了,除了我认为如果
声明错误。我如何说如果(str(i)
包含空格,请加1。
I think I have got this down pretty well, except I think that the if
statement is wrong. How do I say if(str(i)
contains a space, add 1.
编辑:
我发现(感谢Blender)我可以用更少的代码执行此操作:
I found out (thanks to Blender) that I can do this with a lot less code:
function WordCount(str) {
return str.split(" ").length;
}
console.log(WordCount("hello world"));
推荐答案
使用square括号,而不是括号:
Use square brackets, not parentheses:
str[i] === " "
或 charAt
:
str.charAt(i) === " "
你也可以使用 .split()
:
return str.split(' ').length;
这篇关于计算字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文