【简单】算法nodeJs: 统计字符

142 阅读1分钟

描述

对于给定的由可见字符和空格组成的字符串,统计其中英文字母、空格、数字和其它字符的个数。

字符串由 ASCII 码在 32 到 126 范围内的字符组成。您可以参阅下表获得其详细信息。

image.png

输入描述:

在一行上输入一个长度为 1≦length(s)≦1000 的字符串。

输出描述:

第一行输出一个整数,代表字符串中英文字母的个数。
第二行输出一个整数,代表字符串中空格的个数。
第三行输出一个整数,代表字符串中数字的个数。
第四行输出一个整数,代表字符串中其它字符的个数。

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        let tokens = line.split("").map((i) => i.charCodeAt(0));
        const obj = { en: 0, kong: 0, num: 0, other: 0 };
        tokens.forEach((i) => {
            if ((i >= 65 && i <= 90) || (i >= 97 && i <= 122)) {
                obj.en += 1;
            } else if (i == 32) {
                obj.kong += 1;
            } else if (48 <= i && i <= 57) {
                obj.num += 1;
            } else {
                obj.other += 1;
            }
        });
        Object.values(obj).forEach((value) => {
            console.log(value);
        });
    }
})();

第二种解法使用正则表达式

const rl = require("readline").createInterface({ input: process.stdin });

var iter = rl[Symbol.asyncIterator]();

const readline = async () => (await iter.next()).value;

  


void (async function () {

  // Write your code here

  while ((line = await readline())) {

    let a = line.match(/[a-zA-Z]/g) || [];

    let b = line.match(/\s/g) || [];

    let c = line.match(/\d/g) || [];

    let d = line.match(/[^a-zA-Z\s\d]/g) || [];

    console.log(`${a.length}\n${b.length}\n${c.length}\n${d.length}`);

  }

})();