Search code examples
delphipascallazarusfreepascal

How do I split a string into an array of fixed-length substrings?


i try to make a string which has many character,

var
a: String;
b: array [0 .. (section)] of String;
c: Integer;
begin
a:= ('some many ... text of strings');
c:= Length(a);
(some of code)

and make it into array per 10 character. at the last is the remnant of string.

b[1]:= has 10 characters
b[2]:= has 10 characters
....
b[..]:= has (remnant) characters   // remnant < 10

regards,


Solution

  • Use a dynamic array, and calculate the number of elements you need at runtime based on the length of the string. Here's a quick example of doing it:

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    uses
      System.SysUtils;
    
    var
      Str: String;
      Arr: array of String;
      NumElem, i: Integer;
      Len: Integer;
    begin
      Str := 'This is a long string we will put into an array.';
      Len := Length(Str);
    
      // Calculate how many full elements we need
      NumElem := Len div 10;
      // Handle the leftover content at the end
      if Len mod 10 <> 0 then
        Inc(NumElem);
      SetLength(Arr, NumElem);
    
      // Extract the characters from the string, 10 at a time, and
      // put into the array. We have to calculate the starting point
      // for the copy in the loop (the i * 10 + 1).
      for i := 0 to High(Arr) do
        Arr[i] := Copy(Str, i * 10 + 1, 10);
    
      // For this demo code, just print the array contents out on the
      // screen to make sure it works.
      for i := 0 to High(Arr) do
        WriteLn(Arr[i]);
      ReadLn;
    end.
    

    Here's the output of the code above:

    This is a
    long strin
    g we will
    put into a
    n array.