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

Orc*_*ris 63 ruby string indexing

例如,str = 'abcdefg'.如何c使用Ruby在此字符串中找到索引?

kin*_*smk 98

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil
Run Code Online (Sandbox Code Playgroud)

返回str中给定子字符串或模式(regexp)的第一次出现的索引.如果找不到则返回nil.如果存在第二个参数,则它指定字符串中开始搜索的位置.

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

查看ruby文档以获取更多信息.

  • 仅出于完整性考虑,rindex()返回最后一次出现:返回给定子字符串或模式(regexp)在str中最后一次出现的索引。如果找不到,则返回nil。如果存在第二个参数,则它指定字符串中结束搜索的位置-超出此点的字符将不被考虑。[相同来源](http://www.ruby-doc.org/core-1.9.3/String.html) (2认同)

Men*_*nan 25

你可以用它

"abcdefg".index('c')   #=> 2
Run Code Online (Sandbox Code Playgroud)