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

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"

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


当前回答

可以使用字符串元素引用方法,该方法为[]

[]内可以是文本子字符串、索引或正则表达式:

> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil

由于nil在功能上与false相同,并且从[]返回的任何子字符串都是true,因此您可以像使用方法一样使用逻辑。include?:

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" has "abc"

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" does not have "xyz" 

请确保不要将索引与子字符串混淆:

> '123456790'[8]    # integer is eighth element, or '0'
=> "0"              # would test as 'true' in Ruby
> '123456790'['8']  
=> nil              # correct

也可以使用正则表达式:

> s[/A/i]
=> "a"
> s[/A/]
=> nil

其他回答

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

你可以使用include?方法:

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

可以使用字符串元素引用方法,该方法为[]

[]内可以是文本子字符串、索引或正则表达式:

> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil

由于nil在功能上与false相同,并且从[]返回的任何子字符串都是true,因此您可以像使用方法一样使用逻辑。include?:

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" has "abc"

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" does not have "xyz" 

请确保不要将索引与子字符串混淆:

> '123456790'[8]    # integer is eighth element, or '0'
=> "0"              # would test as 'true' in Ruby
> '123456790'['8']  
=> nil              # correct

也可以使用正则表达式:

> s[/A/i]
=> "a"
> s[/A/]
=> nil

三元法

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')

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

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