String processing and safe indexing
Control flow and strings · about 7 min
For the ordinary Delphi strings used in these examples, character positions start at 1. Length returns the number of characters; Pos returns 0 when a substring is absent. Never use the result of Pos as a valid character position until you have checked it. Copy reads a substring; Delete and Insert modify a string. Establish whether a requirement counts letters, words or all characters, because spaces and punctuation change those results.
Normalising the comparison string to uppercase lets you compare A–Z consistently while retaining the original for display. A pangram contains every letter A–Z at least once; repeated occurrences do not compensate for a missing letter. An empty input must return false. This example deliberately tests the English alphabet, not every writing system.
Key points- Use Length, Copy, Pos and character indexing.
- Normalise case when comparing.
- Handle empty strings and missing delimiters.
Worked example: function IsPangram(const sText: string): Boolean; var cLetter: Char; sUpper: string; begin sUpper := UpperCase(sText); Result := True; for cLetter := 'A' to 'Z' do if Pos(cLetter, sUpper) = 0 then begin Result := False; Exit; end; end; The quick brown fox jumps over the lazy dog contains all 26 letters, so it returns True. Removing every z makes the Z check return position 0 and the function exits False. SysUtils supplies UpperCase.
Counting 26 characters or 26 letters does not prove that all distinct letters occur. Accessing sText[1] is unsafe when Length(sText)=0.
Practice: How would you count vowels case-insensitively without counting spaces?
Answer: Loop from 1 to Length(sText), convert each character with UpCase, and increment only if the character is in ['A','E','I','O','U']. Initialise the count before the loop; empty text naturally produces zero.
Recap: Check bounds and missing delimiters; distinguish total occurrences from distinct membership.