Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,847 questions

51,768 answers

573 users

How to split a string into chunks of two characters each in Pascal

1 Answer

0 votes
program SplitStringIntoChunks;

type
  TStringArray = array of string; // Define a named type for the array

function SplitString(const str: string; chunkSize: Integer): TStringArray; // Use the named type
var
  i, len, chunkCount, copyLength: Integer;
  result: TStringArray; // Use the named type
begin
  len := Length(str);
  chunkCount := (len + chunkSize - 1) div chunkSize; // Calculate the number of chunks
  SetLength(result, chunkCount); // Resize the array to store chunks

  for i := 0 to chunkCount - 1 do
  begin
    // Calculate the length of the substring to copy
    copyLength := chunkSize;
    if (i * chunkSize + chunkSize) > len then
      copyLength := len - (i * chunkSize);

    // Extract substring of chunkSize or remaining characters
    result[i] := Copy(str, i * chunkSize + 1, copyLength);
  end;

  SplitString := result; // Return the result array
end;

var
  str: string;
  chunks: TStringArray; // Use the named type
  i: Integer;
begin
  str := 'abcdefghijk';

  // Split the string into chunks
  chunks := SplitString(str, 2);

  WriteLn('Chunks of two characters:');
  for i := Low(chunks) to High(chunks) do
  begin
    WriteLn(chunks[i]);
  end;
end.



(*
run:

Chunks of two characters:
ab
cd
ef
gh
ij
k

*)

 



answered Mar 30, 2025 by avibootz
...