[PerlChina] 如何快速进行等长字符串的按位比较?

Achilles Xu formalin14 at gmail.com
Tue Apr 17 23:53:07 PDT 2007


代码如下:

#!/usr/bin/perl

use strict;
use Inline 'C' => q%
    void compstr(SV* str1, SV* str2)
    {
        STRLEN l1, l2;
        int i;
        char *s1, *s2;
        Inline_Stack_Vars;
        Inline_Stack_Reset;
        s1 = SvPV(str1, l1);
        s2 = SvPV(str2, l2);
        for (i=0;i<l1;i++) {
            if (s1[i] != s2[i]) {
                Inline_Stack_Push(newSViv(i));
            }
        }
        Inline_Stack_Done;
    }
%;

my $a='abcdeafaidnfiowndingfodnsingisdnsod';
my $b='abcbeafaidniiowndingfodnsingisdxsod';

my @r = compstr($a, $b);

print join(' ', at r), "\n";

程序运行结果是:3 11 31(因为是从0开始索引)。

在07-4-18,Achilles Xu <formalin14 at gmail.com> 写道:
>
> 毫无疑问,应该用Inline::C
>
> 在07-4-18,Jester <jester at perlchina.org> 写道:
> >
> > 问个问题,看看大家有没有什么高招。
> > 我需要进行两个"等长"的字符串的"按位"比较,举例而言:
> > $a='abcdeafaidnfiowndingfodnsingisdnsod';
> > $b='abcbeafaidniiowndingfodnsingisdxsod';
> > 我希望做成这样的一个sub,比如叫cmpstr,
> > cmpstr($a,$b)将返回一个array,其中包含了这两个字符串中所有不同的位点的位置。
> > 那么对于上面的例子也就是会返回(4,12,32)。
> > 当然,这只是一个例子,我实际的应用中这两个字符串可能很长,但是肯定是等长的。
> > 目前我知道可以用substr一个一个的提取然后比较,但是我觉得这样会很慢,不知道是否有更加高效的解决方案?
> > 我觉得位运算的效率很高,但是对于我现在的要求好像又不太好用……
> > 请大家帮忙出点高招。
> >
> >
> > Jester
> > _______________________________________________
> > China-pm mailing list
> > China-pm at pm.org
> > http://mail.pm.org/mailman/listinfo/china-pm
>
>
>
>
> --
> ---------------------------
> Achilles Xu
> http://www.lostcode.org




-- 
---------------------------
Achilles Xu
http://www.lostcode.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/china-pm/attachments/20070418/88d06bad/attachment.html 


More information about the China-pm mailing list