7-15 统计数字字符和空格
原题:
本题要求编写程序,输入一行字符,统计其中数字字符、空格和其他字符的个数。建议使用switch语句编写。
输入格式:
输入在一行中给出若干字符,最后一个回车表示输入结束,不算在内。
输出格式:
在一行内按照
blank = 空格个数, digit = 数字字符个数, other = 其他字符个数
的格式输出。请注意,等号的左右各有一个空格,逗号后有一个空格。
.
解题思路:
- 引入
readline
模块并创建接口对象:首先将readline
模块引入,并使用createInterface
方法创建一个接口对象rl
。该对象设置了输入流为标准输入。 - 读取输入并存储:通过监听
'line'
事件,将输入存储在数组buf
中。 - 统计空格、数字和其他字符的数量:初始化
blank
、digit
和other
三个变量分别为0。使用for
循环遍历字符串text
的每个字符,对于每个字符,判断其属于哪一类(空格、数字或其他字符),并将相应的变量+1。 - 输出统计结果:使用模板字符串将结果输出,格式为"blank = x, digit = y, other = z",其中x、y、z分别为第3步中统计得到的空格、数字和其他字符的数量
.
JavaScript(node)代码:
const r = require("readline");
const rl = r.createInterface({
input: process.stdin
});
let buf = [];
rl.on('line', (input) => buf.push(input));
rl.on('close', () => {
const text = buf[0];
let blank = 0, digit = 0, other = 0;
for (let i = 0; i < text.length; i++) {
const char = text.charAt(i);
if (/[a-zA-z]/.test(char)) {
other++;
} else if (/[0-9]/.test(char)) {
digit++;
} else if (char === ' ') {
blank++;
} else {
other++;
}
}
console.log(`blank = ${
blank}, digit = ${
digit}, other = ${
other}`);
});
.