搜索和替换不能在SAS中按预期工作

问题描述

我正在尝试将单词从list1替换为list2(基本上是从一种语言翻译为另一种语言),但是搜索和替换功能无法正常工作。它仅替换thew字符串的一部分,而不替换整个字符串。我做错什么了吗?

运行上面的代码后,我正在运行输出

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

预期输出

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;

解决方法

SAS将字符串存储为固定长度的字符串,并用空格填充。 如果您不告诉别人,SAS将默认字符变量的长度为8。

因此,请定义变量的长度,并在将字符串传递给TRANWRD()函数时使用TRIM()。

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;