Sas 简明教程
SAS - Strings
在 SAS 中,字符串是包含在一对单引号中的值。还需要在变量声明的末尾添加一个空格和 $ 符号,才能声明字符串变量。SAS 具有很多可以分析和操作字符串的强大函数。
Strings in SAS are the values which are enclosed with in a pair of single quotes. Also the string variables are declared by adding a space and $ sign at the end of the variable declaration. SAS has many powerful functions to analyze and manipulate strings.
Declaring String Variables
我们可以声明字符串变量及其值,如下所示。在下面的代码中,我们声明了两个长度分别为 6 和 5 的字符变量。LENGTH 关键字用于声明变量而不创建多个观测值。
We can declare the string variables and their values as shown below. In the code below we declare two character variables of lengths 6 and 5. The LENGTH keyword is used for declaring variables without creating multiple observations.
data string_examples;
LENGTH string1 $ 6 String2 $ 5;
/*String variables of length 6 and 5 */
String1 = 'Hello';
String2 = 'World';
Joined_strings = String1 ||String2 ;
run;
proc print data = string_examples noobs;
run;
在运行上述代码后,我们得到了一个输出,其中显示了变量名及其值。
On running the above code we get the output which shows the variable names and their values.
String Functions
以下是经常使用的一些 SAS 函数的示例。
Below are the examples of some SAS functions which are used frequently.
SUBSTRN
此函数使用起始和结束位置提取子字符串。如果未提及结束位置,它将一直提取到字符串的末尾。
This function extracts a substring using the start and end positions. In case of no end position is mentioned it extracts all the characters till end of the string.
Syntax
SUBSTRN('stringval',p1,p2)
以下是所用参数的描述 -
Following is the description of the parameters used −
-
stringval is the value of the string variable.
-
p1 is the start position of extraction.
-
p2 is the final position of extraction.
Example
data string_examples;
LENGTH string1 $ 6 ;
String1 = 'Hello';
sub_string1 = substrn(String1,2,4) ;
/*Extract from position 2 to 4 */
sub_string2 = substrn(String1,3) ;
/*Extract from position 3 onwards */
run;
proc print data = string_examples noobs;
run;
在运行上述代码后,我们得到了一个显示 substrn 函数结果的输出。
On running the above code we get the output which shows the result of substrn function.
Syntax
TRIMN('stringval')
以下是所用参数的描述 -
Following is the description of the parameters used −
-
stringval is the value of the string variable.
data string_examples;
LENGTH string1 $ 7 ;
String1='Hello ';
length_string1 = lengthc(String1);
length_trimmed_string = lengthc(TRIMN(String1));
run;
proc print data = string_examples noobs;
run;
在运行上述代码后,我们得到了一个显示 TRIMN 函数结果的输出。
On running the above code we get the output which shows the result of TRIMN function.