## `substring` -- extract a substring from a string

#### Introduction

`substring(`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)`

#### Parameters

`string` | - | 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`

#### Returns

a character string.

#### Related Functions

`length`, `strmatch`, `stringlib::subs`

#### Details

- The positions of the characters in a string are indexed from `0` to `length``(string) - 1`.

- The empty string is returned if the length `l` = 0 is specified.
- `substring` is a function of the system kernel.

#### Example 1

We 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 2

The 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:

#### Changes

- no changes

Do you have questions or comments?
Copyright © SciFace Software GmbH & Co. KG 2000