Chuyển đến nội dung

Bài 7 · Basics and Types

Booleans, Characters and Strings in Pascal

Work with Pascal's Boolean, Char and string types: logical values, character codes, short and long strings, indexing, concatenation, Length, Copy, Pos, UpCase and conversions.

Besides numbers, programs handle truth values and text. Pascal has a Boolean type for yes/no answers, a Char type for a single character and a string type for sequences of characters. Strings in Pascal are friendlier than in many languages, but they come in several flavors, so a little history helps.

Pascal code in this lesson is read-only. The C stand-ins at the end show string handling ideas you can run here.

Boolean

A Boolean holds True or False. Comparison operators produce booleans, and and, or, not, xor combine them:

PASCAL
program Bools;

var
  age: Integer;
  isAdult, hasTicket, canEnter: Boolean;

begin
  age := 20;
  hasTicket := True;
  isAdult := age >= 18;
  canEnter := isAdult and hasTicket;
  WriteLn(canEnter);       { TRUE }
  WriteLn(not isAdult);    { FALSE }
end.

Important: and and or have higher precedence than comparisons, so wrap each comparison in parentheses:

PASCAL
if (x > 0) and (x < 10) then ...   { correct }
if x > 0 and x < 10 then ...       { error: 0 and x is evaluated first }

Free Pascal short-circuits and/or by default (the {$B-} setting), so (p <> nil) and (p^.value > 0) is safe. Boolean is an ordinal type with False < True, Ord(False) = 0 and Ord(True) = 1.

Char

A Char holds exactly one character, written in single quotes: 'A', '7', ' '. In Free Pascal's default mode a Char is a single-byte AnsiChar; in Delphi 2009 and later Char is a 16-bit UTF-16 code unit (WideChar). Characters have numeric codes:

PASCAL
var
  c: Char;
begin
  c := 'A';
  WriteLn(Ord(c));        { 65 }
  WriteLn(Chr(66));       { B }
  WriteLn(Succ(c));       { B }
  WriteLn(UpCase('q'));   { Q }
  WriteLn(c in ['A'..'Z']); { TRUE }
end.

Ord converts a character to its code, Chr converts back. UpCase changes a lowercase letter to uppercase; for whole strings use UpperCase and LowerCase from SysUtils. The expression c in ['A'..'Z'] uses a set (see Enumerations, Subranges and Sets).

Strings

A string is a sequence of characters. Pascal historically had three kinds:

Kind Meaning
string[N] / ShortString Fixed capacity of up to 255 characters, length stored in the first byte
AnsiString Long, dynamic, reference counted; no length limit besides memory
UnicodeString Long, UTF-16; the default string in modern Delphi

What plain string means depends on mode: with {$H+} (and in Delphi mode) it is a long, dynamically sized string; with {$H-} it is a short string of at most 255 characters. This course always assumes long strings, so start Free Pascal programs with {$mode objfpc}{$H+}.

Strings are 1-based: the first character is s[1].

PASCAL
{$mode objfpc}{$H+}
program Strs;

var
  s, t: string;
  i: Integer;

begin
  s := 'Pascal';
  t := s + ' rocks';              { concatenation with + }
  WriteLn(t);                     { Pascal rocks }
  WriteLn(Length(t));             { 12 }
  WriteLn(s[1], s[Length(s)]);    { Pl }
  for i := 1 to Length(s) do
    Write(s[i], '-');
  WriteLn;                        { P-a-s-c-a-l- }
end.

Strings may be compared with =, <, > and so on (character by character, case-sensitive) and are copied by value: t := s gives t its own copy as far as your program can tell.

Core string routines

Routine Purpose Example
Length(s) Number of characters Length('abc') is 3
Copy(s, start, count) Substring Copy('Pascal', 2, 3) is asc
Pos(sub, s) Index of first match, 0 if absent Pos('c', 'Pascal') is 4
Insert(sub, s, index) Insert into s
Delete(s, index, count) Remove characters
UpperCase, LowerCase Change case (SysUtils)
Trim(s) Remove surrounding spaces (SysUtils)
IntToStr, StrToInt Convert numbers and text
SetLength(s, n) Resize a string
PASCAL
uses SysUtils;
var
  s: string;
begin
  s := '  Hello, Pascal  ';
  s := Trim(s);                       { 'Hello, Pascal' }
  WriteLn(UpperCase(s));              { HELLO, PASCAL }
  WriteLn(Copy(s, 8, 6));             { Pascal }
  WriteLn(Pos('Pascal', s));          { 8 }
  Delete(s, 1, 7);
  WriteLn(s);                         { Pascal }
end.

Position 0 from Pos means "not found", because indexes start at 1, so a zero test is the way to check.

Converting values

PASCAL
WriteLn(StrToInt('123') + 1);      { 124 }
WriteLn('Total: ' + IntToStr(5));  { Total: 5 }
n := StrToIntDef('abc', -1);       { -1 when the text is not a number }

StrToInt raises an exception on bad text. StrToIntDef returns a default instead, which is safer for user input.

Stand-ins in C

C strings are zero-terminated arrays with 0-based indexes, but the operations (length, copy a slice, search) translate directly. The programs below are C.

C C stand-in: Copy, Pos and Length

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C C stand-in: char codes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the index of the first character of a Pascal string s?

    Pascal strings are 1-based, so s[1] is the first character. A Pos result of 0 therefore means not found.
  2. 2. Why must (x > 0) and (x < 10) have parentheses?

    In Pascal and/or have higher precedence than relational operators, so unparenthesized code is parsed as a mix of integer and boolean operations.
  3. 3. What does Copy('Pascal', 2, 3) return?

    Copy takes 3 characters starting at position 2, which gives asc.
  4. 4. Which function converts text to an integer without raising an exception when the text is invalid?

    StrToIntDef takes a default value that it returns for invalid text. StrToInt raises an exception.

Summary

  • Boolean has True/False; combine with and, or, not, xor, parenthesizing comparisons.
  • Char is one character; Ord and Chr convert to and from codes.
  • Strings are 1-based, concatenated with +; start Free Pascal programs with {$mode objfpc}{$H+}.
  • Learn Length, Copy, Pos, Insert, Delete, Trim, UpperCase, IntToStr, StrToIntDef.

Next: Operators and Expressions

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.