模式匹配是数据结构中字符串的一种基本运算,给定一个子串,要求在某个字符串中找出与该子串相同的所有子串,这就是模式匹配。
假设P是给定的子串,T是待查找的字符串,要求从T中找出与P相同的所有子串,这个问题成为模式匹配问题。P称为模式,T称为目标。如果T中存在一个或多个模式为P的子串,就给出该子串在T中的位置,称为匹配成功;否则匹配失败。
代码如下(示例):
function match(string s1,s2);
int l1,l2;
l1 = s1.len();
l2 = s2.len();
match = 0 ;
if( l2 > l1 )
return 0;
for(int i = 0;i < l1 - l2 + 1; i ++)
if( s1.substr(i,i+l2 -1) == s2)
return 1;
endfunction
程序举例:
program main;
string str1,str2;
int i;
initial
begin
str1 = "this is first string";
str2 = "this";
if(match(str1,str2))
$display(" str2 : %s : found in :%s:",str2,str1);
str1 = "this is first string";
str2 = "first";
if(match(str1,str2))
$display(" str2 : %s : found in :%s:",str2,str1);
str1 = "this is first string";
str2 = "string";
if(match(str1,str2))
$display(" str2 : %s : found in :%s:",str2,str1);
str1 = "this is first string";
str2 = "this is ";
if(match(str1,str2))
$display(" str2 : %s : found in :%s:",str2,str1);
str1 = "this is first string";
str2 = "first string";
if(match(str1,str2))
$display(" str2 : %s : found in :%s:",str2,str1);
str1 = "this is first string";
str2 = "first string ";// one space at end
if(match(str1,str2))
$display(" str2 : %s : found in :%s:",str2,str1);
end
endprogram
因篇幅问题不能全部显示,请点此查看更多更全内容