program StringToCharArrayProgram;
{$mode objfpc}{$H+}
{
This program demonstrates how to convert a string into an
array of characters in Free Pascal.
Modern Pascal strings are convenient to work with, but sometimes
an application may need individual characters stored in a separate
array for processing, validation, parsing, or transformation.
}
type
{
Dynamic array type for storing characters.
A dynamic array is preferred here because its size can be
determined at runtime based on the length of the input string.
}
TCharArray = array of Char;
{
Converts a string into a dynamic array of characters.
Parameters:
AText - Source string.
Returns:
A dynamic array containing all characters from the source string.
Notes:
- Pascal strings are 1-based, meaning the first character is
accessed using index 1.
- Dynamic arrays are 0-based, meaning the first element is
accessed using index 0.
}
function StringToCharArray(const AText: string): TCharArray;
var
I: Integer;
begin
Result := nil;
SetLength(Result, Length(AText));
for I := 1 to Length(AText) do
Result[I - 1] := AText[I];
end;
var
Text: string;
Characters: TCharArray;
I: Integer;
begin
Text := 'Hello, World!';
Characters := StringToCharArray(Text);
WriteLn('Original string: ', Text);
WriteLn;
WriteLn('Character array contents:');
for I := Low(Characters) to High(Characters) do
begin
WriteLn(
'Characters[',
I,
'] = ''',
Characters[I],
''''
);
end;
end.
{
run:
Original string: Hello, World!
Character array contents:
Characters[0] = 'H'
Characters[1] = 'e'
Characters[2] = 'l'
Characters[3] = 'l'
Characters[4] = 'o'
Characters[5] = ','
Characters[6] = ' '
Characters[7] = 'W'
Characters[8] = 'o'
Characters[9] = 'r'
Characters[10] = 'l'
Characters[11] = 'd'
Characters[12] = '!'
}