What is the most effective way in systemVerilog to know how many words a string has?

I have Strings in the following structure:

“cmd, addr, data, data, data, data, ……., \n”

I have to know how many words the String has.

I know that I can go over the String and search for the number of commas, but is there more effective way to do it?

In reply to saritr:

UVM provides a facility to do regexp matching using the DPI, in case you’re already using that. Have a look at the functions in uvm_svcmd_dpi.svh Verilab also provides svlib, a package containing string matching functions.

A simpler option would be to change the commas(,) to a space, then you can use $sscanf (or $fscanf to skip the intermediate string and read directly from a file), assuming each command has a maximum number of words.

int code; // returns the number of words read
string str,word[5];
code = $sscanf(str,"%s %s %s %s %s", word[0],word[1],word[2],word[3],word[4]);

You can use %h if you know a word is in hex and translate it directly to a numeric value instead of a string.