String Manipulation Grade 10

Strings are sequences of characters. Delphi provides built-in functions and procedures to analyse, extract, and modify strings.

What is String Manipulation?

String manipulation is the process of working with text inside a program — searching it, pulling pieces out of it, changing it and measuring it. A string is simply a piece of text: a name, an ID number, an email address or a whole sentence are all strings.

Everyday analogy: Think of a string like a row of bead letters on a piece of string, exactly like a beaded keyring that spells a name. Each bead is one character and it sits in a fixed position. String manipulation is what you do when you slide beads off the end, count how many there are, swap a small to a capital bead, or read which bead is sitting in position 3.

WHY IT MATTERS

Almost every real program handles text. When you log in, the computer compares the string you typed against the stored one. When a website greets you by your first name only, it has extracted that name out of your full name. When a form checks that an email contains an "@", it is searching a string. Learning these functions means you can validate input, format output neatly, and pull useful data out of messy text — skills you will use in every program from here on.

Note: In Delphi, the very first character of a string sits at position 1 (not 0). This is why the reference string below numbers its letters starting at 1.

Reference String

All examples on this page use: sSourceText := 'Andre is cute';

Positions: A=1, n=2, d=3, r=4, e=5, (space)=6, i=7, s=8, (space)=9, c=10, u=11, t=12, e=13

Quick Reference

NameTypeWhat it doesReturns
PosFunctionPosition of a substring in a stringInteger
Index [ ]—Character at a specific positionString (1 char)
CopyFunctionExtract part of a stringString
InsertProcedureInsert text into a stringModifies original
DeleteProcedureRemove part of a stringModifies original
LengthFunctionNumber of characters in a stringInteger
UpperCaseFunctionConvert to all capitalsString
LowerCaseFunctionConvert to all lowercaseString
T2Term 2 · Basic String Methods (Length, UpperCase)

Length — String Length

Syntax
IntegerVariable := Length(SourceText);
Delphi
iX := Length(sSourceText);   // = 13 (length of 'Andre is cute')
iX := Length('Hello');       // = 5

Group 4 — Changing Case

Changing case means turning all the letters into capitals (UpperCase) or all into small letters (LowerCase). The most important reason we do this is to compare text fairly. The computer thinks 'YES', 'yes' and 'Yes' are three different strings, so if you force them all to lowercase first, they all match.

Everyday analogy: Imagine a teacher marking a one-word answer. Whether a learner wrote "Cape Town", "CAPE TOWN" or "cape town", it is the same correct answer. Lowercasing both the answer and the memo before comparing is how you make sure capitals do not unfairly mark someone wrong.

Important Rule: UpperCase and LowerCase return a new string — they do not change the original unless you store the result back into a variable.

UpperCase and LowerCase

Delphi
sResult := UpperCase(sSourceText);
// 'Andre is cute' → 'ANDRE IS CUTE'

sResult := LowerCase(sSourceText);
// 'Andre is cute' → 'andre is cute'
T3Term 3 · Full String Methods & First Principles

Group 1 — Searching a String

Searching means asking "is this smaller piece of text in there, and if so, where?" The answer you get back is a position number. This is the first thing you do before you can extract or change part of a string, because you usually need to know where something is first.

Everyday analogy: It is like using Find (Ctrl+F) in a document. You type a word, and the computer jumps to the spot where it appears and tells you where it is. Pos is Delphi's version of that "Find".

Pos — Find Position

Returns the integer position of the first occurrence of a substring. Returns 0 if not found.

Syntax
IntegerVariable := Pos(StrToBeFound, SourceText);
Delphi
iX := Pos('e', sSourceText);    // = 5  (first 'e' in 'Andre')
iX := Pos('is', sSourceText);   // = 7
iX := Pos('xyz', sSourceText);  // = 0  (not found)

Index [ ] — Character at Position

Access a single character using square brackets and a position number.

Syntax
StringVariable := SourceText[CharacterPosition];
Delphi
sNewText := sSourceText[2];   // = 'n'
sNewText := sSourceText[5];   // = 'e'

Group 2 — Extracting Part of a String

Extracting means taking a copy of a piece of the string without changing the original. You decide where to start and how many characters to grab. This is how you pull a first name out of a full name, a year out of a date, or an area code out of a phone number.

Everyday analogy: Think of cutting a slice out of a loaf of bread. The loaf (the original string) stays whole; you just take a slice from a chosen spot of a chosen thickness. Copy takes the slice, and Index [ ] takes a single thin slice — just one character.

Copy — Extract Substring

Extracts a section of text starting at a position for a given number of characters.

Syntax
StringVariable := Copy(SourceText, BeginPosition, Length);
Delphi
sNewText := Copy(sSourceText, 10, 4);  // = 'cute'  (start at 10, take 4)
sNewText := Copy(sSourceText, 1, 5);  // = 'Andre' (start at 1, take 5)

Group 3 — Changing a String

Changing a string means actually modifying it — adding text in, taking text out, or measuring it. Unlike extracting, these Insert and Delete procedures change the original string directly, so afterwards the string is different from before.

Everyday analogy: This is like editing a sentence in your exercise book. Insert squeezes a new word into the middle of the sentence; Delete rubs a few words out. Length is just counting how many letters the sentence now has.

Insert — Add Text

Inserts text into an existing string at a given position. Modifies the string directly.

Syntax
Insert(InsertText, SourceText, Position);
Delphi
Insert('very ', sSourceText, 10);
// sSourceText is now: 'Andre is very cute'

Delete — Remove Text

Removes a section of text from a string. Modifies the string directly.

Syntax
Delete(SourceText, Position, Length);
Delphi
Delete(sSourceText, 9, 5);
// sSourceText is now: 'Andre is' (removed ' cute')

Practical Patterns

Reverse a String

Delphi
var
  sInput, sReverse: string;
  i: Integer;
begin
  sInput   := edtInput.Text;
  sReverse := '';
  for i := Length(sInput) downto 1 do
    sReverse := sReverse + sInput[i];
  lblResult.Caption := sReverse;
end;

Count Occurrences of a Character

Delphi — count vowels
var
  sText: string;
  i, iCount: Integer;
begin
  sText  := LowerCase(edtInput.Text);
  iCount := 0;
  for i := 1 to Length(sText) do
    if sText[i] IN ['a','e','i','o','u'] then
      Inc(iCount);
  lblResult.Caption := 'Vowels: ' + IntToStr(iCount);
end;

Extract First Name from "Surname, Name"

Delphi — using Pos and Copy
var
  sFullName, sName, sSurname: string;
  iCommaPos: Integer;
begin
  sFullName  := edtInput.Text;           // e.g. 'Smith, John'
  iCommaPos  := Pos(',', sFullName);
  sSurname   := Copy(sFullName, 1, iCommaPos - 1);
  sName      := Copy(sFullName, iCommaPos + 2, Length(sFullName));
  lblOut.Caption := 'Name: ' + sName + '  Surname: ' + sSurname;
end;

Count the Words in a Sentence (Even With Extra Spaces)

Counting the spaces and adding 1 only works when every word is separated by exactly one space. As soon as a learner types two spaces in a row, the answer is wrong. The reliable approach is to count the moments where a new word begins: a non-space character that arrives while you were not already inside a word. A Boolean flag, bInWord, remembers which state you are in.

Delphi — count words using an inWord flag
var
  sSentence: string;
  i, iWords: Integer;
  bInWord: Boolean;
begin
  sSentence := edtSentence.Text;     // e.g. 'Eskom  load   shedding is back'
  iWords  := 0;
  bInWord := False;
  for i := 1 to Length(sSentence) do
    if sSentence[i] = ' ' then
      bInWord := False               // a space ends any word we were in
    else if bInWord = False then   // a letter, and we were NOT in a word yet
    begin
      Inc(iWords);                   // a new word starts here
      bInWord := True;
    end;
  lblResult.Caption := 'Words: ' + IntToStr(iWords);   // 5
end;
Count transitions, not spaces

In 'Eskom load shedding is back' there are 7 spaces but only 5 words. The counter only goes up on the character where a word starts, so extra spaces never matter.

Remove Characters by Building a New String

You cannot "pull" a character out of the middle of a string with a loop easily, and you should not Delete inside a for loop (the positions shift under you). The safe pattern is to start with an empty result string, look at every character of the original, and append only the characters you want to keep.

Delphi — remove all digits (keep everything else)
var
  sText, sClean: string;
  i: Integer;
begin
  sText  := 'Bo2k3aap7';
  sClean := '';
  for i := 1 to Length(sText) do
    if not (sText[i] IN ['0'..'9']) then
      sClean := sClean + sText[i];
  // sClean = 'Bokaap'
end;
Delphi — keep only letters and digits (remove symbols)
sClean := '';
for i := 1 to Length(sText) do
  if sText[i] IN ['A'..'Z', 'a'..'z', '0'..'9'] then
    sClean := sClean + sText[i];
// 'Sipho#12!_Ngcobo'  becomes  'Sipho12Ngcobo'
Delphi — remove every space
sClean := '';
for i := 1 to Length(sText) do
  if sText[i] <> ' ' then
    sClean := sClean + sText[i];
// '082 555 1234'  becomes  '0825551234'

All three versions share the same skeleton; only the if condition changes. Notice the character ranges: 'A'..'Z' means "every character from A to Z" and only works inside a set.

Extract Each Word (Tokens) With Pos, Copy and Delete

To split a sentence into its words, keep finding the next space, copy everything in front of it, then Delete that piece (and the space) from a working copy so the next word moves to the front. Two details make it work:

Delphi — list every word in a memo
var
  sWork, sToken: string;
  iSpace: Integer;
begin
  sWork := edtSentence.Text + ' ';     // e.g. 'Pap en  vleis  op Sondag'
  memOut.Clear;
  iSpace := Pos(' ', sWork);
  while iSpace > 0 do
  begin
    sToken := Copy(sWork, 1, iSpace - 1);   // the text before the space
    if sToken <> '' then                      // skip empty tokens
      memOut.Lines.Add(sToken);
    Delete(sWork, 1, iSpace);              // remove the token AND its space
    iSpace := Pos(' ', sWork);              // find the next space
  end;
end;

The same pattern splits on any separator. For comma-separated data, append ',' instead of a space and search for ','. Because the loop destroys sWork, the original text in edtSentence stays untouched.

Pick a Random Word From a Sentence

A common trick is to choose a random space, throw away everything up to and including it, and then take the word that now sits at the front. Assume the sentence has single spaces and ends with a full stop.

  1. Pick a random position between 1 and the length. Repeat until the character at that position is a space.
  2. Delete from position 1 up to and including that space.
  3. Find the next space with Pos. If there is one, copy the characters before it.
  4. If there is no further space, you picked the last space: copy what is left, except the final full stop.
Delphi — random word after a random space
var
  sRest, sPick: string;
  iPlace, iSpace: Integer;
begin
  Randomize;                                 // once, e.g. in FormCreate
  sRest := 'Table Mountain is covered in cloud.';
  repeat
    iPlace := Random(Length(sRest)) + 1;   // Random(n) gives 0..n-1, so add 1
  until sRest[iPlace] = ' ';
  Delete(sRest, 1, iPlace);                // remove everything up to the chosen space
  iSpace := Pos(' ', sRest);
  if iSpace > 0 then
    sPick := Copy(sRest, 1, iSpace - 1)
  else
    sPick := Copy(sRest, 1, Length(sRest) - 1);   // last word: drop the full stop
  lblWord.Caption := sPick;
end;
TRAP: Random(n) never returns n

Random(Length(sRest)) gives a number from 0 to Length - 1. Position 0 does not exist in a string, so always add 1 to land in the range 1..Length. Also remember that the repeat loop would never finish if the sentence contained no spaces at all.

Palindrome Test

A palindrome reads the same forwards and backwards (for example RACECAR). Build the reverse with a downto loop, then compare the two strings with =. This assumes the text has already been normalised: all the same case and no spaces or punctuation (use UpperCase and the remove-spaces pattern above first).

Delphi — is it a palindrome?
var
  sWord, sBack: string;
  i: Integer;
  bPalindrome: Boolean;
begin
  sWord := 'RACECAR';
  sBack := '';
  for i := Length(sWord) downto 1 do
    sBack := sBack + sWord[i];
  bPalindrome := (sWord = sBack);     // True for RACECAR, False for KAROO
end;

Replace Characters In Place

Because a string is a row of characters you can number, you can overwrite one character by assigning to its position. Replacing keeps the length the same, whereas Insert makes the string longer.

Delphi — replace every hyphen with a space
var
  sPhone: string;
  i: Integer;
begin
  sPhone := '021-555-0147';
  for i := 1 to Length(sPhone) do
    if sPhone[i] = '-' then
      sPhone[i] := ' ';
  // sPhone = '021 555 0147'  (still 12 characters)
end;
Replace vs Insert

sPhone[4] := ' ' overwrites the character at position 4. Insert(' ', sPhone, 4) squeezes a new space in and pushes the rest to the right, so the string grows by one. Copy the text into a string variable first; you cannot assign to one character of edtPhone.Text directly.

Test Membership With IN

IN asks "is this single character one of the members of this set?" The result is Boolean, so it is perfect inside an if. A set can list characters, or use a range such as '0'..'9'.

Delphi — IN with a set
bVowel := cLetter IN ['A','E','I','O','U'];
if sCode[1] IN ['0'..'9'] then
  ShowMessage('Starts with a digit');
TRAP: IN is not a substring search

IN only tests one character against a set of characters. It cannot tell you whether the text 'Pty' appears inside a company name. To search for a piece of text, use Pos and check whether the answer is greater than 0: if Pos('Pty', sName) > 0 then ...

Worked Example — Reading a South African ID Number

A South African ID number is a 13-digit string that packs several pieces of information into fixed positions — a favourite exam question because it uses Length, Copy and the index [ ] all at once.

PositionsMeaningExample (8801235111088)
1–2Year of birth (YY)88
3–4Month (MM)01
5–6Day (DD)23
7–10Gender sequence (5000+ = male)5111 → Male
11Citizenship (0 = SA citizen, 1 = resident)0
12Historically a race indicator; on modern IDs it is always 8 and carries no meaning8
13Check digit (Luhn algorithm)8
Delphi — extract information from an ID
var
  sID, sDOB, sGender, sStatus : string;
  iSeq : Integer;
begin
  sID := edtID.Text;

  // 1. Validate — an ID must be exactly 13 characters long
  if Length(sID) <> 13 then
  begin
    ShowMessage('An ID number must be exactly 13 digits.');
    Exit;
  end;

  // 2. Date of birth — YY at 1, MM at 3, DD at 5 (rebuild as DD/MM/YY)
  sDOB := Copy(sID, 5, 2) + '/' + Copy(sID, 3, 2) + '/' + Copy(sID, 1, 2);

  // 3. Gender — the 4 digits at positions 7-10; 5000 and up = male
  iSeq := StrToInt(Copy(sID, 7, 4));
  if iSeq >= 5000 then
    sGender := 'Male'
  else
    sGender := 'Female';

  // 4. Citizenship — the single character at position 11
  if sID[11] = '0' then
    sStatus := 'SA citizen'
  else
    sStatus := 'Permanent resident';

  // 5. Show the result
  memOut.Lines.Add('Date of birth: ' + sDOB);
  memOut.Lines.Add('Gender: ' + sGender);
  memOut.Lines.Add('Status: ' + sStatus);
end;
The check digit (Grade 11/12 extension)

The 13th digit is a check digit worked out from the other 12 using the Luhn algorithm. A program can recalculate it and compare — if it does not match, the ID was mistyped. That step adds a loop and some arithmetic on top of the string work shown here.

Which function returns the position of a substring in a string?

Pos returns the position of the first occurrence of a substring (0 if not found).

Which function extracts a section of a string?

Copy(source, start, length) extracts a substring without changing the original.

In Delphi, the first character of a string is at position:

Delphi strings are 1-based: the first character is position 1.