perl怎么查找字符串位置

小億
107
2024-06-03 16:44:09

在Perl中,可以使用index函數(shù)來(lái)查找一個(gè)子字符串在另一個(gè)字符串中的位置。

例如,下面是一個(gè)簡(jiǎn)單的示例來(lái)查找子字符串"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個(gè)字符(從0開(kāi)始計(jì)數(shù))。

0