DMarlon Studio

Lesson 12 · 12 of 20

Working with strings · Pascal

Work with text in Pascal: join with +, then Length, Copy, Pos, UpperCase and LowerCase to split an email address into user and domain.

Pascal · Working with strings in DMarlon Studio: the example's code and its output in the terminal

Strings are joined with `+`: first + ' ' + last gives Ada Lovelace. `Length` gives the number of characters, 12.

Each character has a position, which starts at 1: first[1] is 'A', which is how the initials are built. `UpperCase` and `LowerCase`, from SysUtils, return a copy in capitals or small letters; the original string stays as it was.

`Pos(piece, text)` looks for one string inside another and gives the position where it starts: the @ is at 13. If it is not found, it returns 0, as happens with 'xyz'.

`Copy(text, start, count)` cuts out a piece. Using the position of the @, Copy(email, 1, at - 1) takes what comes before it (the user) and Copy(email, at + 1, Length(email) - at) what comes after (the domain).

+ only joins strings: to add a number you first convert it with `IntToStr` (or FloatToStr for real numbers). WriteLn, on the other hand, takes numbers directly when they are separated by commas.

Code · main.pas

program main;uses  SysUtils;var  first, last, full, email, user, domain: String;  at: Integer;begin  first := 'Ada';  last := 'Lovelace';  // + joins strings.  full := first + ' ' + last;  WriteLn('Full name: ', full, ' (', Length(full), ' characters)');  // Characters are numbered from 1.  WriteLn('Initials: ', first[1], last[1]);  WriteLn('In capitals: ', UpperCase(full));  WriteLn('In small letters: ', LowerCase(full));  // Pos finds a piece of text; Copy(s, start, count) cuts one out.  email := 'ada.lovelace@example.com';  at := Pos('@', email);  user := Copy(email, 1, at - 1);  domain := Copy(email, at + 1, Length(email) - at);  WriteLn('The @ is at position ', at);  WriteLn('User: ', user, ' | Domain: ', domain);  WriteLn('Position of "xyz": ', Pos('xyz', email));  // IntToStr turns a number into text, ready to join.  WriteLn('Order ' + IntToStr(1024) + ' for ' + first);end.

Output · fpc main.pas && ./main

Full name: Ada Lovelace (12 characters)
Initials: AL
In capitals: ADA LOVELACE
In small letters: ada lovelace
The @ is at position 13
User: ada.lovelace | Domain: example.com
Position of "xyz": 0
Order 1024 for Ada

Key points

  • + joins strings and Length counts their characters.
  • Positions start at 1: s[1] is the first character.
  • Pos searches (and gives 0 when nothing is found); Copy cuts.
  • IntToStr turns a number into text.

Exercise

Starting from domain, use Pos and Copy to get the company name (example) and the extension (com), and print the user in capitals.