繁体   English   中英

如何使用Perl查找字符串中的元音数量

[英]How to find the number of vowels in a string using Perl

sub Solution{
    my $n=$_[0];
    my $m=lc $_[1];
    my @chars=split("",$m);

    my $result=0;

    my @vowels=("a","e","i","o","u");


    #OUTPUT [uncomment & modify if required]
    for(my $i=0;$i<$n;$i=$i+1){
        for(my $j=0;$j<5;$j=$j+1){
            if($chars[$i]==$vowels[$j]){
                $result=$result+1;
                last;
            }

        }

    }

    print $result;
}



#INPUT [uncomment & modify if required]
my $n=<STDIN>;chomp($n);
my $m=<STDIN>;chomp($m);


Solution($n,$m);

所以我写了这个解决方案来查找字符串中元音的数量。 $n是字符串的长度, $m是字符串。 但是,对于输入3 nam我总是得到输入为3

有人可以帮我调试吗?

==比较数字。 eq比较字符串。 所以你应该写$chars[$i] eq $vowels[$j]而不是$chars[$i]==$vowels[$j] $chars[$i] eq $vowels[$j] 如果您使用过use warnings; ,这是推荐的,你会收到警告。

顺便说一句,没有必要使用额外的长度变量。 您可以使用length()获取字符串的length() ,例如使用scalar()数组的length() 此外,可以使用$#a访问数组@a的最后一个索引。 或者您可以使用foreach迭代数组的所有元素。

更好的解决方案是使用tr运算符,它在标量上下文中返回替换次数:

perl -le 'for ( @ARGV ) { $_ = lc $_; $n = tr/aeiouy//; print "$_: $n"; }' Use Perl to count how many vowels are in each string
use: 2
perl: 1
to: 1
count: 2
how: 1
many: 2
vowels: 2
are: 2
in: 1
each: 2
string: 1

我还包括y ,有时是元音,请参阅: https : //simple.wikipedia.org/wiki/Vowel

让我提出一个更好的方法来计算文本中的字母

#!/usr/bin/env perl
#
# vim: ai:ts=4:sw=4
#

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $debug = 0;             # debug flag

my %count;
my @vowels = qw/a e i o u/;

map{
    chomp;
    my @chars = split '';
    map{ $count{$_}++ } @chars;
} <DATA>;

say Dumper(\%count) if $debug;

foreach my $vowel (@vowels) {
    say "$vowel: $count{$vowel}";
}

__DATA__
So I wrote this solution to find the number of vowels in a string. $n is the length of the string and $m is the string. However, for the input 3 nam I always get the input as 3.

Can someone help me debug it?

输出

a: 7
e: 18
i: 12
o: 12
u: 5

您的代码略有修改形式

#!/usr/bin/env perl
#
# vim: ai:ts=4:sw=4
#

use strict;
use warnings;
use feature 'say';

my $input = get_input('Please enter sentence:');

say "Counted vowels: " . solution($input);

sub get_input {
    my $prompt = shift;
    my $input;

    say $prompt;

    $input = <STDIN>;

    chomp($input);

    return $input;
}

sub solution{
    my $str = lc shift;

    my @chars=split('',$str);

    my $count=0;
    my @vowels=qw/a e i o u/;

    map{
        my $c=$_;
        map{ $count++ if $c eq $_} @vowels;
    } @chars;

    return $count;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM