Javascript 计算字符串的单词数的程序
给定字符串,任务是使用Javascript计算字符串的单词数。单词由以下字符分隔:空格(’ ‘)、换行符(’\n’)、制表符(’\t’)或以上这些的组合。
下面是使用Javascript计算字符串中单词数量的几种方法:
- 使用trim()和split()方法
- 使用正则表达式和match()方法
- 使用for循环
使用trim()和split()方法计算字符串的单词数
在这种方法中,我们将使用trim()方法去除字符串中的前后空格,然后使用split()方法将字符串按一个或多个空格分割。
例子:
Javascript
function wordsLen(str) {
const array = str.trim().split(/\s+/);
return array.length;
}
const str = "Welcome, to the Geeeksforgeeks";
console.log("Word count:" ,wordsLen(str));
输出
Word count: 4
使用JavaScript中的正则表达式和match()方法计算字符串的单词数
在这种方法中,我们将使用match()方法和正则表达式。JavaScript的String match()方法是一种内置的函数,用于根据任何正则表达式搜索字符串。因此,match()将返回包含所有匹配任何非空白字符的字符串的数组。
示例:**
Javascript
function numberOfWords(str) {
const words = str.match(/\S+/g);
if(words.length!==0){
return words.length;
}
else{
return 0;
}
}
const str = "Welcome, to the Geeksforgeeks";
console.log("Word count:", numberOfWords(str));
输出
Word count: 4
使用for循环的JavaScript程序来计算字符串中的单词数
在这种方法中,我们将使用for循环来遍历字符串。
- 我们将创建两个变量“count”用于存储单词的计数和“check”用于跟踪循环是否在单词内部。
- 开始一个
for
循环来遍历输入字符串中的每个字符。 - 检查当前字符不是空格(
' '
)并且check
为false
。这意味着一个新单词正在开始。 -
- 增加
count
以计数这个新单词。 - 将
check
设置为true
以指示循环在单词内。
- 增加
- 如果当前字符是空格(
' '
),则表示一个单词的结束。- 将
check
设置为false
以指示循环不在单词内。
- 将
- 返回计数。
示例:
Javascript
function numberOfWords(str) {
let count = 0;
let check = false;
for (let i = 0; i < str.length; i++) {
if (str[i] !== ' ' && !check) {
count++;
check = true;
} else if (str[i] === ' ') {
check = false;
}
}
return count;
}
const str = "Welcome to the Geeksforgeeks";
console.log("Word count:", numberOfWords(str));
输出
Word count: 4