我有一个包含内容的字符串变量:

varMessage =   
            "hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"


            "/my/name/is/balaji.so\n"
            "call::myFunction(int const&)\n"
            "void::secondFunction(char const&)\n"
             .
             .
             .
            "this/is/last/line/liobrary.so"

在字符串中,我必须找到一个子字符串:

"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

"/my/name/is/balaji.so\n"
"call::myFunction(int const&)\n"

我怎样才能找到它?我需要确定子字符串是否存在。


当前回答

user_input = gets.chomp
user_input.downcase!

if user_input.include?('substring')
  # Do something
end

这将帮助您检查字符串是否包含子字符串

puts "Enter a string"
user_input = gets.chomp  # Ex: Tommy
user_input.downcase!    #  tommy


if user_input.include?('s')
    puts "Found"
else
    puts "Not found"
end

其他回答

一个比Rails(3.1.0及以上版本)中的上述公认答案更简洁的习惯用法是.in?:

my_string = "abcdefg"
if "cde".in? my_string
  puts "'cde' is in the String."
  puts "i.e. String includes 'cde'"
end

我还认为它更可读。

看到了吗?有关详细信息,请参阅文档。

再次注意,它仅在Rails中可用,而不是纯Ruby。

你可以使用include?方法:

my_string = "abcdefg"
if my_string.include? "cde"
   puts "String includes 'cde'"
end

如果你不能使用上面提到的任何一个库,你可以通过简单的文本搜索来实现同样的效果(这是因为降格而忽略大小写):

ADD_BUTTON_TEXTS = ["add to cart", "add to basket"].freeze
target_text = "AdD tO cArT"
ADD_BUTTON_TEXTS.each do |text|
  puts "Text was found" if target_text.downcase.include?(text)
end

如何在Ruby中检查字符串是否包含子字符串?

当您说“check”时,我假设您希望返回一个布尔值,在这种情况下,您可以使用String#match?。火柴接受字符串或正则表达式作为其第一个参数,如果是前者,则会自动转换为正则表达式。因此,您的用例是:

str = 'string'
str.match? 'strings' #=> false
str.match? 'string'  #=> true
str.match? 'strin'   #=> true
str.match? 'trin'    #=> true
str.match? 'tri'     #=> true

字符串#匹配?具有可选的第二个参数的附加优点,该参数指定了从中搜索字符串的索引。默认情况下,该值设置为0。

str.match? 'tri',0   #=> true
str.match? 'tri',1   #=> true
str.match? 'tri',2   #=> false

三元法

my_string.include?('ahr') ? (puts 'String includes ahr') : (puts 'String does not include ahr')

OR

puts (my_string.include?('ahr') ? 'String includes ahr' : 'String not includes ahr')