Turbo Pascal 7.0 Guide
String Processing

Most high-level languages have some built-in functions to make it easier to process data stored as strings. Pascal is no exception.

Strings in Pascal are stored as an array of characters. The following example shows how you can access the individual characters within a string.

VAR name: string;
VAR letter: char;
BEGIN
   name:= 'John Smith';
   letter:= name[6];
END.

When this program executes, the value of the variable letter will be set to equal S.

String Functions

FunctionDescriptionExample
length(string)determines the number of characters in a stringi:= length(mystring);
concat(string1, string2)joins together 2 or more strings - the term for this is concatenationi:= concat(a,b,c);
upcase(char)converts a character to upper case - characters not in the range a..z are not affectedi:=upcase('a');
pos(substring, string)searches for a substring within a string and returns the position of the first occurrence of the substring or 0 if the string is not found.s:= 'JEFFERSON';
i:= pos('SO', s);

i would equal 7
copy(string, startposition, length)returns the substring from the string with the start position and length specified.s: = 'abcdef';
i:= copy(s, 3,4)

i would equal 'cdef'
ord(character)returns the ASCII code for the specified characteri:= ord('a');

String Procedures

ProcedureDescriptionExample
insert(substring, string, startposition)inserts a substring into a string at the start position specified.s:= 'JEFFERSON';
insert(' P', s, 5);

s would now equal 'JEFF PERSON'
delete(string, startposition, length)removes a substring of the specified length from the string, starting at the position specified.s:= 'JEFFERSON';
delete(s, 2,6);

s would now equal 'JON'
str(number, string)attempts to convert the integer or real number to a string - formats can be includedstr(PI:4:2, s);

s would equal '3.14'
val(string, number, conversion)attempts to convert a string expression into a number - if the conversion is possible, the conversion variable is set to 0, otherwise it is set to the value of the position within the string that prevented conversion.val('56', i, c);

i = 56, c = 0

val('18+4', j, d)

j = 0, d = 3

User-defined functions and procedures are discussed later. The main difference is that a function returns a value, a procedure does not.

Exercises

  1. Read in a string and work out how many characters it contains and then convert the entire string to upper case. Remember that case conversion can only be carried out on a char variable.
  2. Set a string to the first line of the outrageous ditty below. Search for each of the spaces within the first line and use the delete procedure to produce the whole rhyme.

    OH SIR JASPER DO NOT TOUCH ME!
    OH SIR JASPER DO NOT TOUCH!
    OH SIR JASPER DO NOT!
    OH SIR JASPER DO!
    OH SIR JASPER!
    OH SIR!
    OH!

  3. Write a program to read in a word and test if it is a palindrome (reads the same forwards as it does backwards).