To replace all occurrences substrings in character variables when working in SAS, you can use the SAS tranwrd() function.

data k;
    a = 'this is a string with some characters and words';
    b = tranwrd(a,"t","mm");
    put b=;
run;

/* Output: */
b=mmhis is a smmring wimmh some characmmers and words

When working with character variables in SAS, the ability to manipulate and easily change the value of those variables is very important.

One such operation which is useful to be able to perform is the ability to replace given characters with other characters in a string.

The SAS tranwrd() function replaces all occurrences of a given string in a string variable.

tranwrd() takes 3 arguments. The first is the variable you want to make replacements in. The second argument is the substring to search for, and the third argument is the substring which will replace any found substrings.

The third argument must have a length greater than 1. If you pass a string with length 0 for the replacement, tranwrd() will use single spaces for the replacement.

Below are some examples of how you can use the SAS tranwrd() function to make replacements in character variables.

data k;
    a = 'this is a string with some characters and words';
    b = tranwrd(a,"t","mm");
    put b=;

    c = 'this is another string';
    d = tranwrd(c,"this","that");
    put d=;

    e = "Hello, my name is Jimmy.";
    f = tranwrd(e, ".","!");
    put f=;
run;

/* Output: */
b=mmhis is a smmring wimmh some characmmers and words
d=that is another string
f=Hello, my name is Jimmy!

Replacing Characters in String Variables with tranwrd() in SAS

There are a few more examples we can go over for how to use tranwrd() to make replacements in character variables in SAS.

For example, if you wanted to replace all underscores in a string with spaces, you could do that easily with the following SAS code.

data k;
    a = 'this_is_a_string';
    b = tranwrd(a,"_"," ");
    put b=;
run;

/* Output: */
b=this is a string

You can do this for other special characters too. For example, if you want to replace dashes with spaces, you can do that as shown below.

data k;
    a = 'this-is-a-string';
    b = tranwrd(a,"-"," ");
    put b=;
run;

/* Output: */
b=this is a string

Hopefully this article has been useful for you to learn how to use the SAS tranwrd() function.

Categorized in:

SAS,

Last Update: February 26, 2024