[英]How do I find the index of a character in a string in Ruby?
For example, str = 'abcdefg'
. 例如, str = 'abcdefg'
。 How do I find the index if c
in this string using Ruby? 如何使用Ruby在此字符串中找到c
?
index(substring [, offset]) → fixnum or nil
index(regexp [, offset]) → fixnum or nil
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. 返回str中给定子字符串或模式(regexp)第一次出现的索引。 Returns nil if not found. 如果找不到则返回nil。 If the second parameter is present, it specifies the position in the string to begin the search. 如果存在第二个参数,则它指定字符串中开始搜索的位置。
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
Check out ruby documents for more information. 查看ruby文档以获取更多信息。
你可以用它
"abcdefg".index('c') #=> 2
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. 希望能帮助到你。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.