Search code examples
delphidelphi-xe

Copy String to StringGrid?


I would like to copy the contents of a Memo to a TStringGrid.

If there is a space or gap between the strings then that word should be added to its own cell in the StringGrid.

So, suppose my Memo which is Wordwrapped contains some information like so:

enter image description here

How could I copy that information into a StringGrid?

For the purpose of this example I have made a sample Image to illustrate how the result should be:

enter image description here

It is important to know that I will not always know the amount of columns to use, if for example the Memo is loaded from a text file.

Maybe a predefined amount of columns would be better such as 5 or 6 columns. The amount of rows will also be unknown.

How may I do this?


Solution

  • If I got you right, then this should do it:

    procedure TForm1.FormClick(Sender: TObject);
    type
      TWordPos = record
        Start, &End: integer;
      end;
    const
      ALLOC_BY = 1024;
    var
      Words: array of TWordPos;
      ActualLength, i: integer;
      txt: string;
      ThisWhite, PrevWhite: boolean;
    begin
    
      ActualLength := 0;
      txt := Memo1.Text;
      PrevWhite := true;
      for i := 1 to Length(txt) do
      begin
        ThisWhite := Character.IsWhiteSpace(txt[i]);
        if PrevWhite and not ThisWhite then
        begin
          if ActualLength = Length(Words) then
            SetLength(Words, Length(Words) + ALLOC_BY);
          Words[ActualLength].Start := i;
          inc(ActualLength);
          PrevWhite := false;
        end else if (ActualLength>0) and ThisWhite then
          Words[ActualLength - 1].&End := i;
        PrevWhite := ThisWhite;
      end;
    
      SetLength(Words, ActualLength);
    
      StringGrid1.RowCount := Ceil(Length(Words) / StringGrid1.ColCount);
    
      for i := 0 to Length(Words) - 1 do
      begin
        StringGrid1.Cells[i mod StringGrid1.ColCount, i div StringGrid1.ColCount] :=
          Copy(Memo1.Text, Words[i].Start, Words[i].&End - Words[i].Start);
      end;
    
    end;
    

    Screenshot