Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

java - Best way to find a substring in a string

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?

Can Ruby provide a better answer? Since we use jRuby the answer can be in Ruby or Java.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Ruby, use the String#include? method:

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

which returns true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...