以下是使用 JavaScript 实现该功能的代码:

function countChars(str) {
  let upperCount = 0;
  let lowerCount = 0;
  let digitCount = 0;
  let specialCount = 0;

  for (let i = 0; i < str.length; i++) {
    let c = str.charAt(i);
    if (c >= 'A' && c <= 'Z') {
      upperCount++;
    } else if (c >= 'a' && c <= 'z') {
      lowerCount++;
    } else if (c >= '0' && c <= '9') {
      digitCount++;
    } else {
      specialCount++;
    } 
  }

  return [upperCount, lowerCount, digitCount, specialCount];
}

// 示例用法
let str = '#HelloWorld123!';
let counts = countChars(str);
console.log(counts); // [2, 8, 3, 2]

此代码将遍历字符串中的每个字符,并根据其属于哪个类别,增加相应的计数器。最后,将计数器的值存储在一个数组中,并将其返回。在示例用法中,字符串'#HelloWorld123!' 的计数器将返回 [2,8,3,2],表示它包含 2 个大写字母,8 个小写字母,3 个数字和 2 个特殊字符。

JavaScript 字符串统计:大写字母、小写字母、数字和特殊字符计数

原文地址: https://www.cveoy.top/t/topic/mxfL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录