3

我有一个字符串(比如字符串 1)需要与另一个字符串(字符串 2)匹配。两个字符串将具有相同的长度并且不区分大小写。

我想打印两个字符串之间的字符匹配数。

E.g.: String 1: stranger
      String 2: strangem

      Match count = 7

我试过这个:

$string1 = "stranger";
$string2 = "strangem";
my $count = $string1 =~ m/string2/ig;

print "$count\n";

我怎样才能解决这个问题?

4

3 回答 3

4

异或,然后计算空字符(字符串相同):

my $string1 = "stranger";
my $string2 = "strangem";
my $count = ( lc $string1 ^ lc $string2 ) =~ tr/\0//;

print "$count\n";

我错过了“不区分大小写”位。

于 2013-11-05T17:07:28.333 回答
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,但我追求的是向后兼容性。)

于 2013-11-05T16:52:40.897 回答
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')
于 2013-11-05T17:03:02.157 回答