在字符串中查找子字符串的最佳方法 [英] Best way to find a substring in a string

查看:119
本文介绍了在字符串中查找子字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我试图在字符串中搜索子字符串。该子字符串可能在字符串中,也可能不在字符串中。

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:


  1. string.indexOf(how are)

  2. 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?方法:

In Ruby, use the String#include? method:

str = "hello how are you?"
substr = "how are"
str.include? substr 

返回 true

这篇关于在字符串中查找子字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆