一、原文题目
Please use systemverilog to implement string find function.
Here are some examples.It will return 3 if we find “cd_” in “a_bcd_123_aaa_232323”.
It will return -1 if we find “f” in “a_bcd_123_aaa_232323”.
The function definition is as following and assume start variant can bigger than 0.
function int find(input string source_str,string substr,int start = 0);
- source_str is the basics string, it is “a_bcd_123_aaa_232323” in above example.
- substr is the looked-up string, it’s “cd_” or “f” in above example.
- start is the start index location of source_str.
substr =“a”,star=0,source_str=“a_bcd_123_aaa_232323”,the function will return 0.
substr =“a”,star=3,source_str=“a_bcd_123_aaa_232323”,the function will return 10.
二、设计与思路
- 题目要求用systemverilog实现在一个长字符串(source_str)中,从start位置开始查找第一个子串(substr)的位置,并返回位置坐标,如果字符串中没有匹配的子串,则返回-1。
- 思路就是首先从字符串(source_str)的start位置开始遍历,查找子串(substr)字符的第一个匹配字符,一旦找到子串(substr)的第一个字符,继续匹配子串(substr)剩下字符,如果匹配完成,则退出遍历返回字符串(source_str)下标减去子串(substr)遍历下标(即为开始值),否则重新匹配子串(substr)第一个字符,直到匹配到或遍历字符串(source_str)结束。代码如下所示:
class find_substr;
function int find(input string source_str,string substr,int start = 0);
int loc=-1;
int i=0,j=0;
for(i=start;i<source_str.len();i++)begin
if(source_str[i]==substr[j])begin
if(j!=substr.len()-1)begin
j++;
end
else begin
loc = i - j;
break;
end
end
else begin
if(j!=0)begin
j = 0;
end
else begin
continue;
end
end
end
return loc;
endfunction
endclass
module tb;
string source_str = "a_bcd_123_sd";
string substr = "d_";
int start = 2;
find_substr fdstr;
initial begin
fdstr = new();
$display("loc is:%0d",fdstr.find(source_str,substr,start));
#200;
$finish;
end
endmodule
三、功能验证
- 代码写完还要验证下功能是否正确,我们设source_str = “a_bcd_123_sd”,substr = “d_”,start=2,然后运行仿真,结果如下,可以观察到location = 4和预期一样。
- 我们再设source_str = “a_bcd_123_sd”,substr = “f”,start=0,然后运行仿真,结果如下,可以观察到location = -1即在字符串中(source_str )没有找到子串(substr )。结合上述仿真可知,本次设计确实达到题目要求。