Counting the number of a string

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
\$str = "abcd/efg/habc/de/abcx";
\$n++ while \$str =~ /abc/g;
print \$n;

Is there a better way (preferably a one-liner)?

TIA
James

Re: Counting the number of a string

On 2/9/2015 01:10, James wrote:

my \$str = "abcd/efg/habc/de/abcx";
my \$n=0;
\$str=~/abc(??{ \$n++ })/g;
print \$n;

Re: Counting the number of a string

# fast

my \$str     = "abcd/efg/habc/de/abcx";
my \$result  = -1;
my \$n       = 0;

for(;;) {
\$result = index \$str, 'abc', 1 + \$result;;
\$result == -1 ? last : \$n++
}

print \$n;

Re: Counting the number of a string

On Tuesday, September 1, 2015 at 4:03:58 PM UTC-7, George Mpouras wrote:

This too works (without modifying \$str):

\$str = "abcd/efg/habc/de/abcx";
print \$str =~ s/abc/abc/g;

Re: Counting the number of a string

Don't know about better, but this works:
\$str = "abcd/efg/habc/de/abcx";
print scalar(()=(\$str =~ m/abc/g));

jue

Re: Counting the number of a string

#!/usr/bin/perl -wl
\$str=shift; \$i = -1; \$n = 0;
while(1) { \$i = index(\$str, "abc", \$i+1); last if (\$i==-1); \$n++}
print \$n
__END__

:r! perl -x % abcd/efg/habc/de/abcx
3
:r! perl -x % cabc4abc4asdfsdafkdfasdfsdfabc
3
:r! perl -x % abcabc
2
:r! perl -x % xbcxbc
0

Elijah
------
not going to win perl golf with that, but might win a benchmark test

Re: Counting the number of a string

On Wednesday, 2 September 2015 03:40:20 UTC+5:30, James  wrote:
[snip]

perl -le '
\$str = "abcd/efg/habc/de/abcx";
\$a++while++(\$b=index(\$str,"abc",\$b//=0));
print \$a//0;
'

Re: Counting the number of a string

-------
\$str = 'aaaaaaaa';

++\$n while \$i = index(\$str, 'aa', \$i) + 1;
print("\$n\n");

\$n = 0;

++\$n for \$str =~ /aa/g;
print("\$n\n");
-------

Which of the two counts would you want for this case?

Re: Counting the number of a string

On Wednesday, 2 September 2015 18:25:48 UTC+5:30, Rainer Weikusat  wrote:
[snip]

Heck yes that's a good catch.

\$str = 'aaaaaaaa';
\$k=length('aa')-1; # korrection factor
\$i+=\$k,++\$n while \$i = index(\$str, 'aa', \$i) + 1;
print("\$n\n");

Re: Counting the number of a string

On Wednesday, September 2, 2015 at 12:38:54 PM UTC-7, shar...@hotmail.com wrote:

A little variations

\$ echo abababab | perl -nle '\$n++,print@-[0] while /a(?=ba)/g; print"\$n matches"'
0
2
4
3 matches

\$ echo abababab | perl -nle '\$n++,print@-[0] while /aba/g; print"\$n matches"'
0
4
2 matches