简体   繁体   English

如何在javascript中计算字符串的每个连续唯一字符的数量

[英]How to count the number of each consecutive unique character of a string in javascript

How to count the number of each consecutive unique character of a string.如何计算字符串中每个连续唯一字符的数量。

Case exampe:
    // Function Name    : CountUniqueChar()
    // Input        : String
    // Output       : Array Object [{k: v}]
    
    // Example : 
    // Input    : “aaaasssiia”
    // output : [{“a”: 4}, {“s”: 3}, {“i”: 2}, {“a”: 1}]

Using matchAll() with a regular expression and map() :matchAll()与正则表达式和map()

 const count = (s) => [...s.matchAll(/(.)\\1*/g)].map(([{length}, c]) => ({[c]: length})); console.log(count('aaaasssiia'));

You can simple achieve this using match and map using /(\\w)\\1*/g您可以使用matchmap使用/(\\w)\\1*/g来简单地实现这一点

在此处输入图片说明

 const str = "aaaasssiia"; const result = str.match(/(\\w)\\1*/g).map((s) => ({ [s[0]]: s.length })); console.log(result);

Use for loop to iterate over each character in a string and compare with next character to keep count of consecutive unique char.使用for loop遍历字符串中的每个字符并与下一个字符进行比较以保持连续唯一字符的计数。

 const input = "aaaasssiia"; const countChar = (str) => { const list = []; let count = 1; for (let i = 0; i < str.length; i++) { if (str[i] === str[i + 1]) { count++ } else { const obj = {}; obj[str[i]] = count; list.push(obj); count = 1; } } return list; } console.log(countChar(input))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM