曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3345|回复: 0
打印 上一主题 下一主题

index --- 查找字串首次出现位置 | rindex --- 查找字串最后一次出现位置

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2011-10-12 15:22:55 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-19 04:30 , Processed in 0.062818 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表