Ruby中的strpos()函数?

16

在 PHP 中有一个有用的函数 strpos,用于查找字符串第一次出现的位置。 Ruby 中是否有类似的方法?

2个回答

30
str.index(pattern)
使用index()方法,如果找到则返回索引值,否则返回nil。
用法:
ruby-1.9.2-p136 :036 > str = "Ruby is awesome"
 => "Ruby is awesome" 
ruby-1.9.2-p136 :037 > str.index("is awesome")
 => 5 
ruby-1.9.2-p136 :038 > str.index("testtest")
 => nil 

1

你可以尝试一下

>> "abc".index("b")
=> 1

或者

>> "acdfeb".match("f").begin(0)
=> 3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接