Can we randomize strings in systemverilog

Can we randomize strings in systemverilog ? for example the below code is giving me the following error :-


 class chk;
   rand string abc;
   
 endclass


module pg;
  chk c1;
  
  initial begin
    c1=new();
    c1.randomize();
    $display("%s \n",c1.abc);
    $finish;
  end
  
endmodule

Errors:



cvlog: *E,RNDVBL (testbench.sv,4|17): Variables declared with the 'rand' modifier must be of an integral or class handle type

In reply to dhpant28:

No, we cannot randomize a string variable. Here is a workaround that I could come up with for generating random strings.


class temp_c;

    rand byte unsigned temp[];

    constraint str_len { temp.size() == 4; } // Length of the string

    constraint temp_str_ascii { foreach(temp[i]) temp[i] inside {[65:90], [97:122]}; } //To restrict between 'A-Z' and 'a-z'

    function string get_str();
        string str;
        foreach(temp[i])  
            str = {str, string'(temp[i])};
        return str;
    endfunction
endclass

module top;

   temp_c obj;

   initial begin
       obj = new;
       obj.randomize();
       $display("\nString is :%0s", obj.get_str());
   end
endmodule

In reply to sharat:

thanks got it :)

In reply to sharat:

Thanks for this Code. I have one question regarding the array declaration. Over here we have made some conditions upon the numbers which are unsigned themselves. So, do we need to specify
" unsigned ". Can we not just write -

rand byte str [];
constraint condition{str.size <= 50;
                     foreach(str[i])
                       str[i] inside {[65:90], [97:122]};}

In reply to Shubhabrata:

For this example, it doesn’t matter. But if the constraints involved numbers bigger than 127, they would be treated as negative.