曲径通幽论坛

标题: index --- 查找字串首次出现位置 | rindex --- 查找字串最后一次出现位置 [打印本页]

作者: beyes    时间: 2011-10-12 15:22
标题: index --- 查找字串首次出现位置 | rindex --- 查找字串最后一次出现位置
index 函数用来查找一个字符串种的字串,并返回这个字串所处的位置(从 0 开始算起)。一般使用如下代码所示:
[Perl] 纯文本查看 复制代码
#!/usr/bin/perl

$big = "hello world";
$small = "wor";

$where = index($big, $small);

print "we got at $where\n";

运行输出:
./index.pl
we got at 6

index 函数还可以使用第 3 个参数,该参数告诉函数要从哪里开始搜索:
[Perl] 纯文本查看 复制代码
#!/usr/bin/perl

my $big = "how world windows";

my $where = index($big, "w");
print "we got at $where\n";

my $where1 = index($big, "w", $where + 1);
print "we got at $where1\n";

my $where2 = index($big, "w", $where1 + 1);
print "we got at $where2\n";

运行输出:
./index.pl
we got at 2
we got at 4
we got at 10

如果函数无法找到字串,那么返回 -1 。

还可以用 rindex 函数找到字串最后一次出现的位置:
[Perl] 纯文本查看 复制代码
#!/usr/bin/perl

my $path = "/home/beyes/perl/";

my $position = rindex($path, "/");

print "$position\n";

运行输出:
./rindex.pl
6





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2