Skip to content

Methods and utilities to manipulate SystemVerilog strings

Here’s a cheatsheet with SystemVerilog string method.

You can play with this example on EDA Playground.

Strings used in the examples below

string s = "porcupine tree";
string p = "pumpkin";
string concat, mult;
string c1, c2;

Concatenate, replicate, length and extract sub-string

// concatenate
concat = {p, " is my ", s};
$display("concat   - %s", concat);
/* Output: concat   - pumpkin is my porcupine tree */

// replicate/multiply
mult = {3{p}};
$display("multiply - %s", mult);
/* Output: multiply - pumpkinpumpkinpumpkin */

// string length
$display("length - %0d", concat.len());
/* Output: length - 28 */

// extract sub-string
$display("substr = %s", s.substr(10, s.len()-1));
// uppercase and lowercase
$display("upper - '%0s' lower - '%0s'", p.toupper(), p.tolower());
/* Output:  upper - 'PUMPKIN' lower - 'pumpkin' */
OUTPUT:

// concatenate
concat   - pumpkin is my porcupine tree

// replicate/multiply
multiply - pumpkinpumpkinpumpkin

// string length
Output: length - 28

// uppercase and lowercase
upper - 'PUMPKIN' lower - 'pumpkin'

Compare strings

// 3 types of compare
c1 = "orange";
c2 = "orAnge";

// returns 0 if strings are not equal
// returns 1 if strings are equal
$display("== : %0d", (c1 == c2));
/* Output: == : 0 */

// C-style strcmp
// returns 0 if strings are equal
// returns > 0 if c1 > c2
// returns < 0 if c1 < c2
$display("compare : %0d", c1.compare(c2));
// similar to above but case insensitive
$display("icompare : %0d", c1.icompare(c2));
/* Output:
 * compare : 32
 * icompare : 0
 */

// replace one character
concat.putc(0, "d");
$display("chars - %s", concat);

Converting between string data type and int, hex, bin, oct and real

Main thing to keep in mind is:

The conversion scans all leading digits and underscore characters ( _ ) and stops as soon as it encounters any other character or the end of the string. It returns zero if no digits were encountered.

/* Output: itoa 1024 */
s.itoa(1024);
$display("itoa %s", s);

/* Output: hextoa 400 */
s.hextoa(1024);
$display("hextoa %s", s);

/* Output: bintoa 10000000000 */
s.bintoa(1024);
$display("bintoa %s", s);

/* Output: octtoa 2000 */
s.octtoa(1024);
$display("octtoa %s", s);

/* Output: realtoa 1024.5 */
s.realtoa(1024.5);
$display("realtoa %s", s);
s = "1024";
/* Output: atoi 1024 */
$display("atoi %0d", s.atoi());

/* Output: atohex 0x1024 (4132)*/
$display("atohex 0x%0x (%0d)", s.atohex(), s.atohex());

/* Output: atobin 0b10 (2) */
$display("atobin 0b%0b (%0d)", s.atobin(), s.atobin());

/* Output: atooct 0o1024 (532) */
$display("atooct 0o%0o (%0d)", s.atooct(), s.atooct());

/* Output: atoreal 1024.500000 */
s = "1024.5";
$display("atoreal %0f", s.atoreal())