温馨提示×

perl如何计算字符串空格数量

小亿
101
2023-10-07 09:54:51
栏目: 编程语言

Perl中可以使用正则表达式和内置函数来计算字符串中空格的数量。

方法一:使用正则表达式匹配空格,然后使用数组上下文将匹配结果保存到数组中,最后返回数组的长度。

use strict;
use warnings;
my $str = "Hello world!";
my @spaces = $str =~ /\s/g;
my $count = scalar @spaces;
print "空格数量:$count\n";

方法二:使用内置函数tr计算字符串中特定字符的数量。在这里,我们将空格作为特定字符。

use strict;
use warnings;
my $str = "Hello world!";
my $count = $str =~ tr/ //;
print "空格数量:$count\n";

无论是使用正则表达式还是使用tr函数,都可以得到字符串中空格的数量。

0