1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
* String manipulation tutorial.
* Replacing / deleting certain characters in strings; combining strings.
* Raynald Levesque.

* Define some dummy data to work with.
DATA LIST FIXED /name 1-25 (A).
BEGIN DATA
000John Doe /10.14.12
0Mary Poppins /17.21
Billy Joe /21.25
000000Peter Pan /10.35
END DATA.
LIST.

* String variables must be defined before being used.
STRING name1 TO name4 (A25).
VARIABLE LABELS name 'Original value' name1 'Without leading zeros' 
		name2 'Replace . by ,' name3 'Delete up to "/"' name4 'Delete from "/"'.

* 1. To delete leading zeros.
COMPUTE name1=LTRIM(name,"0").
LIST name name1.

* 2. To replace dots "." by commas ",".
COMPUTE name2=name1.
* The loop ensures that multiple occurences are covered.
* The "+" ensures that the code would also work as an INCLUDE file.
LOOP IF INDEX(name2,".")>0.
+ COMPUTE SUBSTR(name2,INDEX(name2,"."),1)=",".
END LOOP.
LIST name1 name2.

* 3. To delete the "/" and everything to the left.
COMPUTE name3=SUBSTR(name1,INDEX(name1,"/")+1).
LIST name1 name3.

* 4. To delete the "/" and everything to the right.
COMPUTE name4=SUBSTR(name1,1,INDEX(name1,"/")-1).
LIST name1 name4.

* 5. To concatenate strings str1 and str2.
STRING str1 str2 str3 str4 (A2).
COMPUTE str1="A".
COMPUTE str2="B".
*------- Note that the following does NOT work.
COMPUTE str3=CONCAT(str1,str2).
* It does not work because str1 is actually equal to A followed by a space. Similarly, str2 is B 
  followed by a space.
* Thus CONCAT(str1, str2) results in the 4 character strings "A B ". which is truncated to 
   two character strings "A " to fit the dimension of str3.
*------- The following DOES work.
COMPUTE str4=CONCAT(RTRIM(str1),str2).
LIST str1 str2 str3 str4.
Related pages

...