Quantcast
Channel: How to count string occurrence in string? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

Answer by Ismael Miguel for How to count string occurrence in string?

$
0
0

Here is the fastest function!

Why is it faster?

  • Doesn't check char by char (with 1 exception)
  • Uses a while and increments 1 var (the char count var) vs. a for loop checking the length and incrementing 2 vars (usually var i and a var with the char count)
  • Uses WAY less vars
  • Doesn't use regex!
  • Uses an (hopefully) highly optimized function
  • All operations are as combined as they can be, avoiding slowdowns due to multiple operations

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};

Here is a slower and more readable version:

    String.prototype.timesCharExist = function ( chr ) {        var total = 0, last_location = 0, single_char = ( chr +'' )[0];        while( last_location = this.indexOf( single_char, last_location ) + 1 )        {            total = total + 1;        }        return total;    };

This one is slower because of the counter, long var names and misuse of 1 var.

To use it, you simply do this:

'The char "a" only shows up twice'.timesCharExist('a');

Edit: (2013/12/16)

DON'T use with Opera 12.16 or older! it will take almost 2.5x more than the regex solution!

On chrome, this solution will take between 14ms and 20ms for 1,000,000 characters.

The regex solution takes 11-14ms for the same amount.

Using a function (outside String.prototype) will take about 10-13ms.

Here is the code used:

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};    var x=Array(100001).join('1234567890');    console.time('proto');x.timesCharExist('1');console.timeEnd('proto');    console.time('regex');x.match(/1/g).length;console.timeEnd('regex');    var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};    console.time('func');timesCharExist(x,'1');console.timeEnd('func');

The result of all the solutions should be 100,000!

Note: if you want this function to count more than 1 char, change where is c=(c+'')[0] into c=c+''


Viewing all articles
Browse latest Browse all 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>