String Variables

Many items of data are processed by the computer change their values. They are known as variables and must be declared before use in a var section. The name of the variable (its identifier) must be stated as well as its type. The compiler will keep track of where the variable is stored in memory and make sure that the variable is used in a way that is allowed for its type. For example, it should not be possible to multiply two items of text. The following program will use a variable of type string to represent text.

program Names;
{$APPTYPE CONSOLE}
uses
  SysUtils;
const
  Q1 = 'What is your first name? ';
  GREET_START = 'Hello, ';   
var
  Forename : string;
begin
  write(Q1);
  readln(Forename);
  writeln(GREET_START, Forename);
  readln;
end. 

The readln statement assigns the name typed in by the user to the area of memory named Forename.

We will now extend the program so that it can handle surnames also.

program Names2;
{$APPTYPE CONSOLE}
uses
  SysUtils;
const
  Q1 = 'What is your first name? ';
  Q2 = 'What is your last name? ';
  GREET_START = 'Hello, ';   
var
  Forename, Surname, Fullname : string;
begin
  write(Q1);
  readln(Forename);
  writeln(GREET_START, Forename);
  write(Q2);
  readln(Surname);
  Fullname := Forename + ' ' + Surname;
  writeln(GREET_START, Fullname);
  readln;
end.

The statement, Fullname := Forename + ' ' + Surname; is an assignment. Read ":=" as “becomes equal to”. The three strings (Forename, a single space and Surname) are said to be concatenated (joined together) by the + operator. The resulting string is assigned to the variable Fullname.

Features introduced:
  • Constants declared (using =) before variables

  • Variables declared

  • Input of string

  • Variable assigned using :=

  • Strings concatenated (appended, one immediately after the other) using +

Warning!

A string is composed of characters, each of which may be a letter, symbol or digit. If a string is made up of digits, the + operator will concatenate the strings rather than add the digits. Can you predict the output of the following program?

program ConcatenateDigitStrings;
{$APPTYPE CONSOLE}
var
  DigitString : string;
begin
  DigitString := '1' + '2';
  writeln(DigitString);
  readln;
end.    
Programming - a skill for life!

The various types of constants and variables and how to use them