Grade 11 · String manipulation · Lesson and coding task · about 16 minutes
Open this task in the Delphi workspace →
Every character has a number — its ASCII/ordinal value. Ord('A') is 65, Ord('B') is 66 … and Chr(65) turns 65 back into 'A'. Which means you can do maths on letters:
Chr(Ord('A') + 1) // 'B' - the next letter
That is the engine of the Caesar cipher: shift every letter along the alphabet. One problem — shift 'Z' by 3 and you fall off the end. The fix is to wrap around:
iCode := Ord(cLetter) + iShift;
if iCode > Ord('Z') then
iCode := iCode - 26; // wrap Z back to A
To decide whether a character even is a letter, use a set: if cLetter in ['A'..'Z'] then … — anything else (spaces, digits) passes through unchanged.
Your task
Encrypt a message: uppercase it, shift each letter by the given amount (wrapping after Z), and leave non-letters alone.
What you will do
- Uppercase the word; read the shift from edtShift
- Shift each letter with Chr(Ord(…) + iShift), wrapping past 'Z'
- Non-letters (like spaces) stay unchanged
- lblCode shows the encrypted message
Hints
- Test for a letter with if cLetter in ['A'..'Z'] then
- Shift: iCode := Ord(cLetter) + iShift; then if iCode > Ord('Z') then iCode := iCode - 26;
- Build the answer like a running total: sCode := sCode + Chr(iCode);
Model solution
procedure TfrmSecret.btnEncodeClick(Sender: TObject);
var
sWord, sCode : String;
i, iShift, iCode : Integer;
cLetter : Char;
begin
sWord := UpperCase(edtWord.Text);
iShift := StrToInt(edtShift.Text);
sCode := '';
for i := 1 to Length(sWord) do
begin
cLetter := sWord[i];
if cLetter in ['A'..'Z'] then
begin
iCode := Ord(cLetter) + iShift;
if iCode > Ord('Z') then
iCode := iCode - 26;
sCode := sCode + Chr(iCode);
end
else
sCode := sCode + cLetter;
end;
lblCode.Caption := sCode;
end;