温馨提示×

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

小亿
120
2023-10-07 09:54:51
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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函数,都可以得到字符串中空格的数量。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:perl怎么计算字符串长度

0