Home > Archive > PERL Beginners > July 2004 > Count the occurence of a character
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Count the occurence of a character
|
|
| Jaffer Shaik 2004-07-23, 8:56 am |
| Dear Friends,
I have the below strig
$str = "abckdweqadidkaaaaisdikda";
In the above string, I want to count the occurrences of character 'a',
i.e I should get count of a = 7.
How can i achieve this in Perl.
Thank you,
Jaffer.
| |
| Remo Sanges 2004-07-23, 8:56 am |
| On Jul 23, 2004, at 11:42 AM, Jaffer Shaik wrote:
> $str = "abckdweqadidkaaaaisdikda";
>
> In the above string, I want to count the occurrences of character 'a',
> i.e I should get count of a = 7.
>
> How can i achieve this in Perl.
>
@a=$str=~m/a/g;
print scalar(@a)."\n";
Remo
| |
| Paul Johnson 2004-07-23, 8:56 am |
| On Fri, Jul 23, 2004 at 03:12:22PM +0530, Jaffer Shaik wrote:
> I have the below strig
>
> $str = "abckdweqadidkaaaaisdikda";
>
> In the above string, I want to count the occurrences of character 'a',
> i.e I should get count of a = 7.
>
> How can i achieve this in Perl.
$count = $str =~ tr/a//;
See "Regexp Quote-Like Operators" in perldoc perlop.
--
Paul Johnson - paul@pjcj.net
http://www.pjcj.net
| |
| David Storrs 2004-07-24, 3:55 am |
|
On Fri, Jul 23, 2004 at 12:13:48PM +0200, Paul Johnson wrote:
> On Fri, Jul 23, 2004 at 03:12:22PM +0530, Jaffer Shaik wrote:
>
>
> $count = $str =~ tr/a//;
Note that this modifiees the string. You might want to do
$count = $str =~ tr/a/a/;
instead.
--Dks
| |
| John W. Krahn 2004-07-28, 8:56 pm |
| David Storrs wrote:
> On Fri, Jul 23, 2004 at 12:13:48PM +0200, Paul Johnson wrote:
>
>
> Note that this modifiees the string. You might want to do
>
> $count = $str =~ tr/a/a/;
>
> instead.
They both modify the string and in fact they both do exactly the same thing.
perldoc perlop
[snip]
Otherwise, if the REPLACEMENTLIST is
shorter than the SEARCHLIST, the final character is replicated till
it is long enough. If the REPLACEMENTLIST is empty, the SEARCHLIST
is replicated. This latter is useful for counting characters in a
class or for squashing character sequences in a class.
John
--
use Perl;
program
fulfillment
|
|
|
|
|