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

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"

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


当前回答

你也可以这样做。。。

my_string = "Hello world"

if my_string["Hello"]
  puts 'It has "Hello"'
else
  puts 'No "Hello" found'
end

# => 'It has "Hello"'

本例使用Ruby的String#[]方法。

其他回答

如果大小写无关,那么不区分大小写的正则表达式是一个很好的解决方案:

'aBcDe' =~ /bcd/i  # evaluates as true

这也适用于多行字符串。

有关更多信息,请参阅Ruby的Regexp类。

一个比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。

三元法

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