我有一个字符串(比如字符串1)需要与其他字符串匹配(string2) 两个字符串都具有相同的长度,并且不区分大小写。
我想打印两个字符串之间的字符匹配数。
Eg: String 1: stranger
String 2: strangem
Match count = 7
我试过了:
$string1 = "stranger";
$string2 = "strangem";
my $count = $string1 =~ m/string2/ig;
print "$count\n";
感谢任何形式的帮助。在此先感谢!!
答案 0 :(得分:4)
排他或,然后计算零字符(字符串相同):
my $string1 = "stranger";
my $string2 = "strangem";
my $count = ( lc $string1 ^ lc $string2 ) =~ tr/\0//;
print "$count\n";
更新:错过了“案例不敏感”位。
答案 1 :(得分:3)
您可以使用substr:
#!/usr/bin/perl
use warnings;
use strict;
my $string1=lc('stranger');
my $string2=lc('strangem');
my $count=0;
for (0..length($string1)-1) {
$count++ if substr($string1,$_,1) eq substr($string2,$_,1);
}
print $count; #prints 7
或者您可以使用split将所有字符作为数组获取,并循环:
#!/usr/bin/perl
use warnings;
use strict;
my $string1=lc('stranger');
my $string2=lc('strangem');
my $count=0;
my @chars1=split//,$string1;
my @chars2=split//,$string2;
for (0..$#chars1) {
$count++ if $chars1[$_] eq $chars2[$_];
}
print $count; #prints 7
(fc
提供比lc
更准确的结果,但我追求向后兼容。)
答案 2 :(得分:0)
未经测试
sub cm
{
my @a = shift;
my @b = shift;
# First match prefix of string:
my $n = 0;
while ($n < $#a && $n < $#b && $a[$n] eq $b[$n]) {
++$n;
}
# Then skip one char on either side, and recurse.
if ($n < $#a && $n < $#b) {
# Match rest by skipping one place:
my $n2best = 0;
my $n2a = cm(splice(@a, $n), splice(@b, $n + 1));
$n2best = $n2a;
my $n2b = cm(splice(@a, $n + 1), splice(@b, $n));
$n2best = $n2b if $n2b > $n2best;
my $n2c = cm(splice(@a, $n + 1), splice(@b, $n + 1));
$n2best = $n2c if $n2c > $n2best;
$n += $n2best;
}
return $n;
}
sub count_matches
{
my $a = shift;
my $b = shift;
my @a_chars = split //, $a;
my @b_chars = split //, $b;
return cm(@a_chars, @b_chars);
}
print count_matches('stranger', 'strangem')