如何在 Ruby 中找到字符串中字符的索引?

例如,使用 Ruby,如果 c在这个字符串中,我如何找到索引?

122872 次浏览

你可以用这个

"abcdefg".index('c')   #=> 2
index(substring [, offset]) → fixnum or nil
index(regexp [, offset]) → fixnum or nil

返回 str 中给定子字符串或模式(regexp)的第一个匹配项的索引。如果没有找到,返回空。如果存在第二个参数,则指定开始搜索的字符串位置。

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

查看 Ruby 文件了解更多信息。

str="abcdef"


str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">

希望能有所帮助