有没有更好的方法来计算字符串中出现的字符? [英] Is there a better way to count occurrence of char in a string?

查看:21
本文介绍了有没有更好的方法来计算字符串中出现的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得一定有更好的方法来统计发生次数,而不是在Linux中用Perl或shell编写SUB。

#/usr/bin/perl -w
use strict;
return 1 unless $0 eq __FILE__;
main() if $0 eq __FILE__;
sub main{
    my $str = "ru8xysyyyyyyysss6s5s";
    my $char = "y";
    my $count = count_occurrence($str, $char);
    print "count<$count> of <$char> in <$str>
";
}
sub count_occurrence{
    my ($str, $char) = @_;
    my $len = length($str);
    $str =~ s/$char//g;
    my $len_new = length($str);
    my $count = $len - $len_new;
    return $count;
}

perl

计算字符串中字符的出现次数在推荐答案中只需一行(而不是4行)。不需要SUB(尽管将功能封装在SUB中没有什么问题)。发件人perlfaq4 "How can I count the number of occurrences of a substring within a string?"

use warnings;
use strict;

my $str = "ru8xysyyyyyyysss6s5s";
my $char = "y";
my $count = () = $str =~ /Q$char/g;
print "count<$count> of <$char> in <$str>
";

这篇关于有没有更好的方法来计算字符串中出现的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆