繁体   English   中英

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

[英]How do I find the index of a character in a string in Ruby?

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

index(substring [, offset]) → fixnum or nil
index(regexp [, offset]) → fixnum or nil

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

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

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

你可以用它

"abcdefg".index('c')   #=> 2
str="abcdef"

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

希望能帮助到你。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM