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

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"

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


当前回答

你可以使用include?方法:

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

其他回答

你可以使用include?方法:

my_string = "abcdefg"
if my_string.include? "cde"
   puts "String includes 'cde'"
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。

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

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

> 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