Count repeated letters in a string

前端 未结 7 1841
耶瑟儿~
耶瑟儿~ 2021-01-06 02:06

I\'m stuck with the following problem: I need to find repeated characters in a string. Basically what I want is regular expression that will match like that



        
相关标签:
7条回答
  • 2021-01-06 02:18
    function charCount(str){
        let arr = str.split('');
        return arr.reduce((a,p)=>{
            a[p] = a[p] ? (a[p]+1) : 1;
            return a;
        },{});
    };
    
    0 讨论(0)
  • 2021-01-06 02:22

    var re = /([a-z])(?:.*)(\1)+/g; 
    var str = ['aaaccbcdd'];
    var m;
    var result = new Array();
    
    for(var i = 0; i < str.length; i++) {
      result[i] = str[i] + "->";
      while ((m = re.exec(str[i])) !== null) {
          if (m.index === re.lastIndex) {
              re.lastIndex++;
          }
          // View your result using the m-variable.
          // eg m[0] etc.
        result[i] += m[1];
        result[i] += m[2] + ",";
      }
    }
    
    document.getElementById("results").innerHTML = result.join("</br>");
    <div id="results"></div>

    0 讨论(0)
  • 2021-01-06 02:25

    You can use

    ([a-zA-Z]).*(\1)
    

    Demo regex


    Since you have clarified that you are looking for a solution that will handle something other than double letters in a string, you should use a non-regex approach such as:

    Build an associative array with the count of the characters in the string:

    var obj={}
    var repeats=[];
    str='banana'
    
    for(x = 0, length = str.length; x < length; x++) {
        var l = str.charAt(x)
        obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
    }
    
    console.log(obj)
    

    Prints

    { b: 1, a: 3, n: 2 }
    

    Then build an array of your specifications:

    for (var key in obj) {
        if (obj.hasOwnProperty(key) && obj[key]>1) {
            repeats.push(new Array( obj[key]+ 1 ).join( key ));
        }
    }
    console.log(repeats)
    

    Prints:

    [ 'aaa', 'nn' ]
    
    0 讨论(0)
  • 2021-01-06 02:25

    For your scenario you second solution seems better. You can get the second letter by other capture group

    Regex you be (it is your 2nd RegEx with more one capture group):

    /([a-z])(?:.*)(\1)+/g
    

    var re = /([a-z])(?:.*)(\1)+/g; 
    var str = ['hello', 'here', 'happiness', 'pupil'];
    var m;
    var result = new Array();
    
    for(var i = 0; i < str.length; i++) {
      result[i] = str[i] + "->";
      while ((m = re.exec(str[i])) !== null) {
          if (m.index === re.lastIndex) {
              re.lastIndex++;
          }
          // View your result using the m-variable.
          // eg m[0] etc.
        result[i] += m[1];
        result[i] += m[2] + ",";
      }
    }
    
    document.getElementById("results").innerHTML = result.join("</br>");
    <div id="results"></div>

    0 讨论(0)
  • 2021-01-06 02:25

    This method also works well!!

    let myString = 'abababc';
    let result = {};
    for (let str of myString) {
      result[str] = result.hasOwnProperty(str) ? result[str] + 1 : 1;
    }
    console.log(result);
    

    The result will be like this {a: 3, b: 3, c: 1}

    0 讨论(0)
  • 2021-01-06 02:29
    var obj = {};
    var str = "this is my string";
    for (var i = 97; i < 97 + 26; i++) 
      obj[String.fromCharCode(i)] = 0;
    for (var i = 0; i < str.length; i++) {
      obj[str.charAt(i).toLowerCase()]++;
    }
    

    From there you can say obj["a"] to get the number of occurrences for any particular letter.

    0 讨论(0)
提交回复
热议问题