在字符串中查找子字符串的最佳方法
问题描述:
我有一个问题,我试图在字符串中搜索子字符串。该子字符串可能在字符串中,也可能不在字符串中。
I have a problem where I am trying to search for a substring in string. That substring may or may not be in the string.
str = "hello how are you?"
substr = "how are"
我知道可以做的两种方式是:
Two ways which I know if can be done are:
-
string.indexOf(how are)
- regex
但是,还有其他优化方式吗?你会做什么?
But, is there any other "optimized" way? What would you have done?
Ruby可以提供更好的答案吗?由于我们使用jRuby,答案可以是Ruby或Java。
Can Ruby provide a better answer? Since we use jRuby the answer can be in Ruby or Java.
答
在Ruby中,使用字符串#include? code>方法:
In Ruby, use the String#include?
method:
str = "hello how are you?"
substr = "how are"
str.include? substr
返回 true
。