touque.ca > Education Commons > Programming: Concepts > Substrings

Concepts

Substrings

Recall that a string is a set of characters treated as a whole. It follows, then, that a substring is a subset of those characters, also treated as a whole.

Consider the string “pineapple”. This string has a length of 9, because it is composed of 9 characters: p, i, n, e, a, p, p, l, e. The substring which consists of just the first character is “p”; the substring which consists of just the first four characters is “pine”; the substring which consists of just the 5th to last characters is “apple”; and the substring which consists of just the last character is “e”—not to be confused with the substring which consists of just the 4th character, which is also “e”.

In Turing, substrings are indicated with an integer expression in parentheses following the string, which may be a string literal, declared constant, or string variable. Consider the sample code which follows.

Output statements

% Declaration Section

const CARMENS_FRUIT := "pineapple"
var fruit : string


% Initialization section

fruit := CARMENS_FRUIT


% Each of the following triplets produces the
% same results in the run window.

put CARMENS_FRUIT (1)
put fruit (1)
put "pineapple" (1)

put CARMENS_FRUIT (1 .. 4)
put fruit (1 .. 4)
put "pineapple" (1 ..4)

put CARMENS_FRUIT (5 .. *)
put fruit (5 .. *)
put "pineapple" (5 .. *)

put CARMENS_FRUIT (*)
put fruit (*)
put "pineapple" (*)

Other valid uses

Of course, substrings aren’t restricted to output statements. In fact, substrings can be used anywhere it’s valid to use a string, as the following code illustrates.

% Declaration Section

const CARMENS_FRUIT := "pineapple" (5 .. *)

var fruit : string
var french_article : string
var tree : string


% Initialization section

fruit := "pineapple plant" (1 .. 9)
tree := fruit (1 .. 4)
fruit := fruit (5 .. *)
french_article := fruit (* - 1 .. *)

Built-in functions

Two built-in functions are particularly useful in the manipulations of substrings: length, which returns the length of a given string, and index, which returns the position of the first occurrence of a substring in a given string—or zero, if the substring does not occur in the given string. Following are some examples

% Declaration Section

const CARMENS_FRUIT := "pineapple"

var fruit : string


% Initialization section

fruit := CARMENS_FRUIT


% Each of the following triplets produces the
% same results in the run window.

put length (CARMENS_FRUIT)
put length (fruit)
put length ("pineapple")

put index (CARMENS_FRUIT, "a")
put index (fruit, "a")
put index ("pineapple", "a")

put index (CARMENS_FRUIT, "x")
put index (fruit, "x")
put index ("pineapple", "x")

touque.ca > Education Commons > Programming: Concepts > Substrings