Cheat sheet: strings without tears

Go down

Cheat sheet: strings without tears

· #1

A 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

pascal
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 workhorse

One 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.

Re: Cheat sheet: strings without tears

· #2

Bookmarked. The "pointer and a prayer" row should be in the official docs.

Re: Cheat sheet: strings without tears

· #3

Good sheet. One addition for the list of things that bite: Pos returns 0 for "not found", not -1. Everyone coming from another language gets that wrong once.

Read the error message. Then read it again.

Re: Cheat sheet: strings without tears

· #4

Added in my head. I'll edit the post I'll edit the post when the forum lets me edit without losing my place.

Go up

Sign in to reply