簡體   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