租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

perl如何计算字符串空格数量,perl怎么用

发布时间:2023-10-07 09:54:51

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

Perl中可使用正则表达式和内置函数来计算字符串中空格的数量。
方法一:使用正则表达式匹配空格,然后使用数组上下文将匹配结果保存到数组中,最后返回数组的长度。

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

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

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

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