Remember:
substr(T,N,L)
is a Pascal function that
outputs
the substring of T
that begins at position
N
and that has length = L.
Suppose that S := 'Algorithm'.
For each of the following,
(i) What do they compute?
(ii)
Can you describe what they do in a
general way?
d- substr(S, 1, length(S)-1)
e- substr(S, 2, length(S)-1)
f- substr(S, 2, length(S)-2)
Answers:
d- if S = 'Algorithm', then this returns 'Algorith';
i.e., it returns all but
the last character of S
Why? Because it takes
S, finds the 1st character
(which is 'A'), computes
"length(S)-1" (which is
9-1, which is 8), and then
returns the substring
that begins with 'A' and
is 8 characters long.
e- if S = 'Algorithm', then this returns 'lgorithm';
i.e., it returns all but
the first character of S
Why? Because it takes
S, finds the 2nd
character (which is 'l'),
computes "length(S)-1"
(which, as we just saw,
is 8), and then returns
the substring that begins
with 'l' and is 8
characters long.
f- This takes S, finds the 2nd character (which,
as we just saw, is 'l'),
computes "length(S)-2"
(which is 9-2, which is
7), and then returns
the substring that begins
with 'l' and is 7
characters long.
i.e., if S = 'Algorithm',
then this returns 'lgorith';
i.e., it returns all but
the first and last
characters of S
If you are still not sure about the English descriptions
of what these do in general, try several different
strings as input so that you can begin to see the
patterns.
Here are 2 more to try:
g- substr(S, length(S) , 1)
h- substr(S, length(S-1), 2)
Click
here for the answers and the rest of these
lecture
notes.