search and replace not working in sas as expected

556 views Asked by At

I am trying to replace the words from list1 to list2 (basically translating from one language to another), but the search and replace function is not working as expected. It only replaces a portion of thew string and not the complete. Am I doing something incorrect?

Output I am running after running the code above:

names_list                                         names_list_french                                  i
My name is Craig Matthews, My name is Donald Dunn  Je m'appis Craig Matthews, Je m'appis Donald Dunn  3

Expected Output:

names_list                                         names_list_french                                  i
My name is Craig Matthews, My name is Donald Dunn  Je m'appelle Craig Matthews, Je m'appelle Donald Dunn  3

SAS CODE:
data datatable;
names_list="My name is Craig Matthews, My name is Donald Dunn";
array list1{2} $ _temporary_ (
"My name is Craig Matthews",
"My name is Donald Dunn"
);
array list2{2} $ _temporary_ (
"Je m'appelle Craig Matthews",
"Je m'appelle Donald Dunn"
);
names_list_french=names_list;
put names_list= names_list_french=;
do i=1 to dim(list1);
put list1{i}= list2{i}=;
names_list_french=tranwrd(names_list_french,list1{i},list2{i});
end;
put names_list= names_list_french=;
run;
1

There are 1 answers

1
Tom On BEST ANSWER

SAS stores strings as fixed length padded with spaces. If you do not tell it otherwise SAS will default character variables to length of 8.

So define the length of your variables and use TRIM() when passing the strings to TRANWRD() function.

data datatable;
  length names_list $100;
  names_list="My name is Craig Matthews, My name is Donald Dunn";
  array list1{2} $100 _temporary_ (
    "My name is Craig Matthews",
    "My name is Donald Dunn"
  );
  array list2{2} $100 _temporary_ (
    "Je m'appelle Craig Matthews",
    "Je m'appelle Donald Dunn"
  );
  names_list_french=names_list;
  put names_list= names_list_french=;
  do i=1 to dim(list1);
    put list1{i}= list2{i}=;
    names_list_french=tranwrd(names_list_french,trim(list1{i}),trim(list2{i}));
  end;
  put names_list= names_list_french=;
run;