TStringGrid
has the function of filling non-existent cells whose cells are outside of ColCount * RowCount
. Thus, there is no need to count words before filling the grid of rows.
Then a direct approach leads to:
procedure TForm1.Button1Click(Sender: TObject); var WordCount: Integer; WordStart: Integer; S: String; I: Integer; begin WordCount := 0; WordStart := 1; S := Memo.Text + ' '; for I := 1 to Length(S) do if S[I] = ' ' then begin if WordStart <> I then begin Grid.Cells[WordCount mod Grid.ColCount, WordCount div Grid.ColCount] := Copy(S, WordStart, I - WordStart); Inc(WordCount); end; WordStart := I + 1; end; Grid.RowCount := ((WordCount - 1) div Grid.ColCount) + 1; end;
Note. . To prevent additional memory allocation for text (due to the addition of ' '
), add the last word to the grid after the loop.
Bonus Function:
To set up column counting, reclassify the row grid as follows, and all cells will be automatically rearranged:
type TStringGrid = class(Grids.TStringGrid) protected procedure SizeChanged(OldColCount, OldRowCount: Integer); override; end; TForm1 = class(TForm) ... procedure TStringGrid.SizeChanged(OldColCount, OldRowCount: Integer); var I: Integer; begin if OldColCount < ColCount then begin for I := 0 to OldColCount * OldRowCount - 1 do Cells[I mod ColCount, I div ColCount] := Cells[I mod OldColCount, I div OldColCount]; end else if OldColCount > ColCount then begin for I := OldColCount * OldRowCount - 1 downto 0 do Cells[I mod ColCount, I div ColCount] := Cells[I mod OldColCount, I div OldColCount]; end; if OldColCount <> OldRowCount then for I := OldColCount * OldRowCount to ColCount * RowCount - 1 do Cells[I mod ColCount, I div ColCount] := ''; end;
source share