awill
awill

Reputation: 135

how to search string inside another string in system verilog?

If I want to know if string a is included string qwerty, is there an easy way to do this in system verilog? Like below code in C?

a.strstr("qwerty");

Upvotes: 2

Views: 21611

Answers (4)

Maverick Blogger
Maverick Blogger

Reputation: 1

    module test;
      string mainString = "hello world";
      string subString = "rld";

      initial begin
        for (int i=0; i<mainString.len()-subString.len()+1; i++) begin
          if( mainString.substr(i,i+subString.len()-1) == subString ) begin
            $display("\n it Contraints \n");
          end
        end
      end
  endmodule 

Upvotes: 0

nmz787
nmz787

Reputation: 2170

Based on the answer by awill I coded these two functions:

function int contains(string a, string b);
  // checks if string A contains string B
  int len_a;
  int len_b;
  len_a = a.len();
  len_b = b.len();
  $display("a (%s) len %d -- b (%s) len %d", a, len_a, b, len_b);
  for( int i=0; i<len_a; i++) begin
    if(a.substr(i,i+len_b-1) == b)
         return 1;
  end
  return 0;
endfunction


function int startswith(string a, string b);
  // checks if string A starts-with string B
  int len_b;
  len_b = b.len();
  if(a.substr(0, len_b-1) == b)
    return 1;
  return 0;
endfunction

Upvotes: 2

Tudor Timi
Tudor Timi

Reputation: 7573

You can use the svlib library from Verilab that wraps the C functions we know and love in SystemVerilog functions. It provides its own Str class that can tell you if a string contains a certain substring:

Str my_str = Str::create(a);
if my_str.first("qwerty")
  $display("found it");

You can find svlib at this location

Upvotes: 1

awill
awill

Reputation: 135

currently i do it this way, it works. but i am wondering if there is a better way...

int len = a.len();
for( int i =0; i < len;i++) begin
    if(a.substr(i,i+6-1) =="qwerty")
       $display("found it");
end

Upvotes: 4

Related Questions