在字符串中查找特定字符
Find a specific character in a string
我想在给定的数字字符串中查找特定字符,例如,如果我的输入是:
1 4 5 7 9 12
那么 4
的答案应该是 1
。我的代码如下:
secarr = second.split(" ")
answer = secarr.index(number) #here number is a variable which gets the character
puts answer
如果我写 "4"
而不是 number
或任何其他特定字符,则上述方法有效,但如果我写变量,则上述方法无效。 ruby 中是否有方法可以做到这一点?
这可能是你的变量number
是一个Integer,而secarr是一个Array of Strings
。尝试将数字转换为字符串:
answer = secarr.index(number.to_s)
我想在给定的数字字符串中查找特定字符,例如,如果我的输入是:
1 4 5 7 9 12
那么 4
的答案应该是 1
。我的代码如下:
secarr = second.split(" ")
answer = secarr.index(number) #here number is a variable which gets the character
puts answer
如果我写 "4"
而不是 number
或任何其他特定字符,则上述方法有效,但如果我写变量,则上述方法无效。 ruby 中是否有方法可以做到这一点?
这可能是你的变量number
是一个Integer,而secarr是一个Array of Strings
。尝试将数字转换为字符串:
answer = secarr.index(number.to_s)