CSCI 150, Spring 2003
Home | | Course Schedule | | Assignments | | Lecture Notes
A. Concatenating strings:
Use a + sign to concatenate two strings together. For example if word1, word2 and
message are all variables of the string type, then the following code will write out
'Happy Birthday':
word1 := 'Happy '; word2 := 'Birthday'; message := word1 + word2; writeln(message);
B. Extracting a part of a string
Use the function, copy(stringName, start, number ), to extract a part of the string.
The three pieces of information in the parentheses following copy are 1) the name
of the string variable, 2) the number of the first character in the substring you want
to extract, and 3) the length of the substring you want to extract.
For example:
word1 := 'Hannah'; word2 := copy(word1, 2, 4); writeln( word2);
The above lines of code will write out 'anna'. The function copy( word1, 2, 4) will start with the second letter of word1 and copy 4 letters altogether, resulting in the new string, 'anna'.
C. Finding the length of a string:
Use the function, length(stringName), to find the length of the string.
word1 := 'apple pie'; writeln('The length of the string is ', length(word1));
The above code will write out: 'The length of the string is 9'
You can use the length function to copy all the characters from a middle character to the end of a string:
word1 := 'apple pie'; word2 := copy(word1, 2, length(word1) - 1); writeln(word2);
The above code will write out 'pple pie' to the monitor (i.e. it removes the first letter from the string).
D. Finding the position of one string inside another:
Use the function, pos(string1, string2) to locate the position of the first string
within the second string. This function will return the position of the first letter of
string1 where it occurs in string2. If the first string is not contained in the second
string, the pos(string1, string2) will return 0.
word1 := 'ace'; word2 := 'traces'; writeln( word1, ' occurs at position ', pos(word1, word2), ' in ', word2);
The above code will write out: 'ace occurs at position 3 in traces'