简体   繁体   English

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

[英]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.

相关问题 如何在 ruby 的字符串中的每个字符之间添加字符? - How do I add characters between each character in a string in ruby? 在 Ruby 中,如何替换字符串中的问号字符? - In Ruby, how do I replace the question mark character in a string? 在 Ruby 中,如何找到元素数组之一的索引? - In Ruby how do I find the index of one of an array of elements? 在ruby中,如何找到给定字符串的第一个非空白字符的索引 - In ruby, how to find the index of first non-whitespace character of given string 如何在 Ruby 中查找字符串是否以另一个字符串开头? - How do I find if a string starts with another string in Ruby? 如何在 Ruby 中查找和匹配字符串中的唯一字母? - How do I find and match unique letters in a string in Ruby? 在 Ruby 中,如何确定字符串是否不在数组中? - In Ruby, how do I find out if a string is not in an array? 如何让Ruby将字符串的索引视为字符(而不是ASCII代码)? - How can I get Ruby to treat the index of a string as a character (rather than the ASCII code)? 如何在Ruby中将以&#39;H&#39;开头的10个字符的子字符串与更长的字符串匹配? - How do I match a 10 character sub-string starting with 'H' in a longer string with Ruby? 如何在Ruby正则表达式中放置转义字符(不是“转义”字符)? - How do I put an escape character (NOT “escaped” character) in a Ruby regex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM