string - 如何获取字符串开头对应字符的个数

标签 string perl compare

我有两个字符串,例如$must$is。它们在开始时应该是相同的。但是如果有错误,我想知道在哪里。

例子:

my $must = "abc;def;ghi";
my $is   = "abc;deX;ghi";

位置 6 上的“X”不相等,所以这是我需要的结果。

所以我需要类似的东西

my $count = count_equal_chars($is, $must);

结果是“6”,因为字符 0 到 5 相等。 (如果是“5”也没关系,因为写++没问题。)

到目前为止我的代码:

编辑:添加了解决方法。

#!/usr/bin/perl

use strict;
use warnings;
use utf8;

my $head_spec = "company;customer;article;price"; # specified headline
my $count = 0;                                    # row counter

while (<DATA>) {
    s/[\r\n]//;      # Data comes originally from Excel ...
    if (!$count) {
        # Headline:

        ## -> error message without position:
        ##print "error in headline\n" unless ($head_spec eq $_);

        ## -> writeout error message with position:
        next if ($head_spec eq $_);
        # Initialize char arrays and counter
        my @spec = split //, $head_spec; # Specified headline as character-array
        my @is   = split //, $_;         # Readed    headline as character-array
        my $err_pos = 0;                 # counter - current position
        # Find out the position:
        for (@spec) {
             $err_pos++, next if $is[$err_pos] eq $_;
             last;
        }
        # Writeout error message
        print "error in headline at position: $err_pos\n";
    }
    else {
        # Values
        print "process line $count, values: $_\n";
    }
}
continue { $count++; }

__DATA__
company;custXomer;article;price
Ser;0815;4711;3.99
Ser;0816;4712;4.85

背景:
背景是,有一个带有很长标题(> 1000 个字符)的 .csv 文件。此 header 指定。 如果其中有错误,则该文件有错误,必须由用户编辑。 所以告诉他错误在哪里很有用,这样他就不需要比较整行了。

最佳答案

使用xor^,算子可以找到错误的位置。在连续字母匹配的地方,异或运算给出 \0.

$-{0]last match start variable (对于上一行中的正则表达式, (($must ^ $is) =~/[^\0]/)。

你可以这样找到位置:

#!/usr/bin/perl
use strict;
use warnings;

my $must = "company;customer;article;price";
my $is   = "company;custXomer;article;price";


($must ^ $is) =~ /[^\0]/; # find first non-matching character

print "Error position is ", $-[0];  # position of first non-matching char

打印:12

关于string - 如何获取字符串开头对应字符的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67584968/

相关文章:

python - 从字符串创建子字符串列表

css - 在文件中提取特定的 css 类

Java,检查字符串是否为回文。不区分大小写

php - Sql 查询查找两个给定日期之间的 View 百分比差异

regex - 如何将一个字符串附加到文件中所有出现的另一个字符串

string - EXCEL VBA : extracting 8 digits sequence from a string in cell

javascript - 从字符串 JavaScript 中选择多个子字符串

perl - 如何构造哈希的哈希

perl - 在不同的文本文件中查找共同条目

sql - 在 Oracle 中使用 SQL 检查表是否相同