Welcome to WebmasterWorld Guest from 107.22.87.145

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Determining how many times a string appears in a string

     
2:57 pm on Oct 30, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2004
posts:681
votes: 0


Is there a way to determine the number of instances a string appears in a larger string like here [javascript.internet.com], except in Perl, not JavaScript?
4:56 pm on Oct 30, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 8, 2003
posts:659
votes: 0


This should do it, even with regular expressions:

my $string = "substring substring substring oefiojoifasubstringioafesjvaiosubstring";
my $count = 0;
my $flag = 0;
do {
if ( $string =~ /substring/) {
$string = $';
$count++;
} else {
$flag = 1;
}
} until $flag == 1;

print "$count\n";

5:01 pm on Oct 30, 2004 (gmt 0)

Full Member

10+ Year Member

joined:Mar 3, 2004
posts:270
votes: 0


This is answered in the Perl FAQ that ships with perl. Type this at the command line:

perldoc -q count

5:03 pm on Oct 30, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 8, 2003
posts:659
votes: 0


"There's More Than One Way To Do It"
12:01 am on Nov 1, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member kaled is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Mar 2, 2003
posts:3710
votes: 0


I think something like this will work.

$tmp = $str;
$count = ($tmp ~= s/$search//g);

i.e. a global substitute with a null string.
I'm not certain the syntax above is correct - my perl is a bit rusty.

Kaled.

9:50 am on Nov 3, 2004 (gmt 0)

Junior Member from US 

10+ Year Member

joined:Nov 30, 2002
posts:162
votes: 0


kaled has the right idea, but this syntax works:

my $count = ($string =~ tr/$substring//);
12:32 pm on Nov 4, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2004
posts:681
votes: 0


Thanks everyone!
3:46 pm on Nov 4, 2004 (gmt 0)

Senior Member

WebmasterWorld Senior Member drdoc is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Mar 15, 2002
posts:6807
votes: 0


Here's yet another possibility:

$count = @{[$string =~ /$match/g]};