[Israel.pm] count chars

Pinkhas Nisanov pinkhas at nisanov.com
Mon Sep 3 07:42:12 PDT 2007


Hi,

On 9/3/07, Amir E. Aharoni <amir.aharoni at gmail.com> wrote:
> What is the best way to count the number of times that a character
> appears in a string?

if you need good performance, use "Inline::C".
e.g.:


use Inline C;

print "Char in Str: ". chCnt( 'a', 'ajhajhhjajhjajh' ). "\n";
### you get:
### Char in Str: 4

__DATA__
__C__

int chCnt ( char lookChar, char *str  ) {
  char c;
  int i = 0;
  int currCnt = 0;

  while ( c = str[i++] )
    {
      if ( c == lookChar )
	{
	  ++currCnt;
	}
    }

  return currCnt;
}



More information about the Perl mailing list