C provides a number of string functions that can be useful to an RPG
programmer. The example we have chosen to illustrate is strtok. This function
can be used to break up a string into a series of “tokens”. One use for this is to
break up a description into its component words. We may want to do this so that
we can eliminate multiple embedded blanks or certain special characters from the
text, or simply to count the number of words used.
strtok allows you to specify which characters are to be considered the “delimiter”
for these tokens. By this, we mean the individual characters (such as space,
period, and comma) that mark the boundaries between tokens. The function also
allows you to change the group of characters that represents the delimiter on
each call to the function.

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
h dftactgrp(*no) actgrp(*caller) option(*srcstmt)
h bnddir('QC2LE')

d counter s 3s 0
d displayme s 20
d isodate s d inz
d n12 s 12s 0
d pointer s *
d reply s 1
d response s 4096a
d rundte s 6s 0
d token S 160A varying
d DS

dstrtok PR * ExtProc('strtok')
d string * value options(*string)
d delim * Value Options(*string)

/free

response = 'tree,dog,bird,,cow,horse,flower';
response = %scanrpl(',,' : ', ,' : response);
reset counter;
pointer = strtok(response: ',');

dow (pointer <> *null);
counter+=1;
token = %trim(%str(pointer));
pointer = strtok(*null: ',');
displayme = %trim(token);
dsply displayme reply;
enddo;

*inlr = *on;

found old example read to array not using STRTOK

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
D string s 100A
D len s 10I 0
D x s 10I 0
D lastpos s 10I 0
D pos s 10I 0 dim(50)
D field s 52A

c eval string = 'Test||||||123|x|||8900'

c eval lastpos = 1
c '|' scan string pos

c for x = 1 to %elem(pos)

c if pos(x) = 0
c leave
c endif

c eval len = pos(x) - lastpos
c eval field = %subst(string:lastpos:len)
c field dsply

c eval lastpos = pos(x) + 1
c endfor

c eval *inlr = *on

another old example read to variable not using STRTOK

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
D string s 100A
D len s 10I 0
D lastpos s 10I 0
D pos s 10I 0
D field s 52A

c eval string = 'Test||||||123|x|||8900'
c eval lastpos = 1

c dou pos = 0

c eval pos = %scan('|': string: lastpos)
c if pos = 0
c leave
c endif

c eval len = pos - lastpos
c eval field = %subst(string:lastpos:len)
c field dsply

c eval lastpos = pos + 1
c enddo

c eval *inlr = *on


Upload files



 


STRTOK – reading single field/ multiple values by delimiter
Tagged on:     

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.