Reading — step 1 of 5
Learn
~1 min readStrings, Arrays, Types
Pascal strings are first-class. FreePascal has multiple string types — for now, just use the default string (which in modern FPC is AnsiString, dynamically allocated).
var
s, t: string;
begin
s := 'Hello';
t := ' Pascal';
WriteLn(s + t + '!'); { Hello Pascal! }
WriteLn(Length(s)); { 5 }
WriteLn(Copy(s, 2, 3)); { 'ell' (1-indexed!) }
end.
Key string operations:
Length(s)— character counts[i]— character at position i (1-indexed!)s + t— concatenationCopy(s, start, count)— substringPos(needle, haystack)— index of first match (0 if not found)Insert(value, target, pos)— insert in-placeDelete(s, pos, count)— remove in-place
SysUtils for more — uses SysUtils; at the top:
UpperCase(s),LowerCase(s)Trim(s),TrimLeft(s),TrimRight(s)StringReplace(s, old, new, [rfReplaceAll])Format('%s = %d', [name, value])— printf-styleIntToStr(n),StrToInt(s)FloatToStr(x),StrToFloat(s)
uses SysUtils;
var s: string;
begin
s := ' hello world ';
WriteLn('[' + Trim(s) + ']'); { [hello world] }
WriteLn(UpperCase(s)); { HELLO WORLD }
WriteLn(StringReplace(s, 'world', 'Pascal', [rfReplaceAll]));
WriteLn(Format('len=%d', [Length(s)])); { len=15 }
end.
Iterating characters:
for i := 1 to Length(s) do
WriteLn(s[i]);
for c in s do { for-in (FPC 3.x) }
WriteLn(c);
char type — single character (as in 'a'):
var c: char;
begin
c := 'A';
WriteLn(Ord(c)); { ASCII code: 65 }
WriteLn(Chr(97)); { 'a' }
end.
Old-school string[N] — fixed-size, 1-indexed with length byte. Mostly historical; modern FPC's string is dynamic.
For heavy text processing, FreePascal also has WideString (UTF-16, COM compatible) and UnicodeString (FPC 2.7+, UTF-16/UTF-8 depending on platform). For learning, plain string is fine.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…