Cheat sheet: strings without tears
· #1A short reference for the questions that come up every week. Corrections welcome.
The types
| Type | What it holds | Use it when |
|---|---|---|
AnsiString (string with {$H+}) |
Bytes, usually UTF-8 | Almost always |
UnicodeString |
UTF-16 | Talking to an API that wants it |
ShortString |
Up to 255 bytes | You miss 1989 |
PChar |
A pointer and a prayer | A C library insists |
Things that bite
Length(S)counts bytes, not characters.Length('é')is 2 in UTF-8.- Strings start at index 1. Yes, really. No, it will not change.
Copy(S, 1, 3)can cut a character in half.
The functions you actually use
uses SysUtils, StrUtils;
S := Trim(S); // spaces off both ends
S := LowerCase(S); // ASCII only
if S.StartsWith('http') then ... // type helpers are fine
Parts := S.Split([',']); // array of string
N := StrToIntDef(S, 0); // no exception, a default
S := Format('%d of %d', [I, Count]); // the workhorseOne rule
Decide the encoding at the edges of your program and keep it the same in the middle.
That's it. That's the whole sheet.