我有一个包含内容的字符串变量:
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
可以使用字符串元素引用方法,该方法为[]
[]内可以是文本子字符串、索引或正则表达式:
> 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