温馨提示×

perl怎么查找字符串位置

小亿
90
2024-06-03 16:44:09
栏目: 编程语言

在Perl中,可以使用index函数来查找一个子字符串在另一个字符串中的位置。

例如,下面是一个简单的示例来查找子字符串"world"在字符串"hello world"中的位置:

my $str = "hello world";
my $substr = "world";

my $pos = index($str, $substr);

if ($pos != -1) {
    print "The substring '$substr' was found at position $pos\n";
} else {
    print "The substring '$substr' was not found\n";
}

上述代码将输出:“The substring ‘world’ was found at position 6”,表示子字符串"world"在字符串"hello world"中的位置是第6个字符(从0开始计数)。

0