如何在 Ruby 中找到字符串中字符的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10668415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the index of a character in a string in Ruby?
提问by Orcris
For example, str = 'abcdefg'. How do I find the index if cin this string using Ruby?
例如,str = 'abcdefg'。如果c在这个字符串中使用 Ruby,我如何找到索引?
回答by kingasmk
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. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
返回给定子字符串或模式 (regexp) 在 str 中第一次出现的索引。如果未找到,则返回 nil。如果存在第二个参数,则它指定字符串中开始搜索的位置。
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
Check out ruby documentsfor more information.
查看ruby 文档以获取更多信息。
回答by Mennan
You can use this
你可以用这个
"abcdefg".index('c') #=> 2
回答by kiddorails
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
希望能帮助到你。:)

