我有一个包含内容的字符串变量:
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"
我怎样才能找到它?我需要确定子字符串是否存在。
如何在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
如何在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