santu4frnds has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a string like 'dftaatzaaadfaa'.I need a count of 'aa' in a string.

Replies are listed 'Best First'.
Re: Count of Repeated Characters
by davido (Cardinal) on Apr 27, 2015 at 04:06 UTC

    It's customary to show what you've tried and to explain where you're stuck. Providing actual sample input and output is also helpful. The specification you have provided is incomplete; for example, what output do you want if the string is "aaa"? Are overlaps included or excluded from your result set?

    But most importantly, this site is about helping people to understand and grow as Perl programmers. Questions that don't demonstrate an interest in that process are often off-topic here.


    Dave

      Thanks for the reply. I tried splitting the two characters at a time from the string and able to get the count. But my requirement is to include the overlap as well that's where I am struck.

Re: Count of Repeated Characters
by karlgoethebier (Abbot) on Apr 27, 2015 at 12:14 UTC
    "...I need a count of 'aa' in a string."

    If you only want to count the occurance of 'aa' (only two letters - you wrote 'aa') try this:

    print scalar grep {$_ eq 'aa'} split /[^a]/, 'dftaatzaaadfaa';

    This one counts at two or more occurances of a:

    print scalar grep {/aa/} split /[^a]/, 'dftaatzaaadfaa';

    Please see also scalar, grep, split and perlretut

    Update: Fixed typos

    Update 2: Yes, i know - some might say this is yet another "misuse". But it works:

    karls-mac-mini:monks karl$ perl -MData::Dump -E 'dd split /[^a]/, qq( +dftaatzaaadfaa)'; ("", "", "", "aa", "", "aaa", "", "aa") karls-mac-mini:monks karl$ perl -E 'say scalar grep {$_ eq 'aa'} split + /[^a]/, qq(dftaatzaaadfaa)'; 2 karls-mac-mini:monks karl$ perl -E 'say scalar grep {/aa/} split /[^a] +/, qq(dftaatzaaadfaa)'; 3

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Re: Count of Repeated Characters
by chacham (Prior) on Apr 27, 2015 at 18:08 UTC

    3 or 4. :)

    Does 'aaa' count as 1 or 2: '(aa)a' and 'a(aa)'?