我有一个包含内容的字符串变量:
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
如何在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