【问题标题】:Splitting a numerical string in Perl在 Perl 中拆分数字字符串
【发布时间】:2012-10-13 19:47:32
【问题描述】:

我有一个数字字符串:

"13245988"

我想在连续数字之前和之后分割。

预期输出是:

1
32
45
988

这是我尝试过的:

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

my $a="132459";
my @b=split("",$a);
my $k=0;
my @c=();
for(my $i=0; $i<=@b; $i++) {
    my $j=$b[$i]+1;
    if($b[$i] == $j) {
        $c[$k].=$b[$i];
    } else {
        $k++;
        $c[$k]=$b[$i];
        $k++;
    }
}
foreach my $z (@c) {
    print "$z\n";
}

【问题讨论】:

  • 连续的数字?
  • 我猜想“成对的连续整数数字”是什么意思,比如3 24 5(但不是1 3)。但是你为什么不在98 之后分开呢?哦,还有你试过什么?
  • Jean,你猜对了。我尝试了下面的代码。但我得到不同的输出。使用严格;使用警告;我的 $a="132459";我的@b=split("",$a);我的 $k=0;我的@c=(); for(我的 $i=0;$i
  • Jean,对于预期输出中的错误,我们深表歉意。预期输出为 1 32 45 988。

标签: string perl split


【解决方案1】:

根据已澄清的问题进行编辑。像这样的东西应该可以工作:

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

my $a = "13245988";
my @b = split("",$a);

my @c = ();
push @c, shift @b; # Put first number into result.

for my $num (@b) { # Loop through remaining numbers.

    my $last = $c[$#c] % 10; # Get the last digit of the last entry.

    if(( $num <= $last+1) && ($num >= $last-1)) {
        # This number is within 1 of the last one
        $c[$#c] .= $num; # Append this one to it
    } else {
        push @c, $num; # Non-consecutive, add a new entry;
    }
}

foreach my $z (@c) {
    print "$z\n";
}

输出:

1
32
45
988

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
  • @dgw 我已经根据澄清的问题进行了编辑,希望现在可以。
  • 嗨,Rob,代码运行良好。我不明白这部分代码“my $last = $c[$#c] % 10;”。你能详细说明一下吗?希望你不要介意。非常感谢。
  • @Iam,% 是模运算符:my $c = $a % $b;$a 除以$b,并将余数分配给$c。您可以在man perlop找到更多详细信息。
猜你喜欢
  • 2013-11-08
  • 2013-07-07
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 2013-05-28
  • 2014-08-06
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多