Reputation: 4835
I'm trying to find solution, how can I split string like this:
abkgwvc
to array
by character? Expected output is:
array[0] = a
array[3] = g
...
any idea?
for i := 0 to length(string) do
begin
array[i] = copy(string, i, 1);
end;
Upvotes: 0
Views: 18577
Reputation: 125708
A string can be accessed as an array of characters directly, so there's no need to use Copy
. The example below is based on versions of Delphi/Lazarus that support dynamic arrays, but you can use an old-style fixed length array (Arr: array[..] of Char
) the same way; just remove the SetLength
call and change the declaration to the right array type.
var
Str: string;
Arr: array of Char;
i: Integer;
Len: Integer;
begin
Str := 'abkgwvc';
Len := Length(Str);
SetLength(arr, Len);
// Dynamic arrays are 0-based indexing, while
// strings are 1 based. We need to subtract 1
// from the array index.
for i := 1 to Len do
Arr[i - 1] := Str[i];
end;
(Of course, if you're not using dynamic arrays, it's not clear why you'd need a separate array in the first place; you can just access the string char-by-char directly.)
Upvotes: 7