substring -- extract a
substring from a string
Introductionsubstring(string, i) returns the
(i+1)-st character of a string.
substring(string, i, l) returns the
substring of length l starting with the
(i+1)-st character of the string.
substring(string, i..j) returns the
substring consisting of the characters i+1 through
j+1.
Call(s)substring(string, i)
substring(string, i, l)
substring(string, i..j)
Parametersstring |
- | a nonempty character string |
i |
- | an integer between 0 and length(string) - 1 |
l |
- | an integer between 0 and length(string) - i |
j |
- | an integer between i and length(string) - 1 |
Returnsa character string.
Related
Functionslength, strmatch, stringlib::subs
DetailsThe positions of the characters in a string are
indexed from 0 to length(string) - 1.
l =
0 is specified.substring is a function of the system kernel.
Example
1We extract individual characters from a string:
>> substring("0123456789", i) $ i = 0..9
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
Substrings of various lengths are extracted:
>> substring("0123456789", 0, 2), substring("0123456789", 4, 4)
"01", "4567"
Substrings of length 0 are empty strings:
>> substring("0123456789", 4, 0)
""
Ranges may be used to specify the substrings:
>> substring("0123456789", 0..9)
"0123456789"
Note that the position of the characters is counted from 0:
>> substring("123456789", 4..8)
"56789"
Example
2The following while loop removes all trailing blank
characters from a string:
>> string := "MuPAD ":
while substring(string, length(string) - 1) = " " do
string := substring(string, 0..length(string) - 2)
end_while
"MuPAD"
The following for loop looks for consecutive blank
characters in a string and shrinks such spaces to a single blank
character:
>> string := "MuPAD - the open computer algebra system":
result := substring(string, 0):
space_count := 0:
for i from 1 to length(string) - 1 do
if substring(string, i) <> " " then
result := result . substring(string, i);
space_count := 0
elif space_count = 0 then
result := result . substring(string, i);
space_count := space_count + 1
end_if
end_for:
result
"MuPAD - the open computer algebra system"
>> delete string, result, space_count, i: