我想将备忘录的内容复制到 TStringGrid。
如果字符串之间有空格或间隙,则应将该单词添加到 StringGrid 中其自己的单元格中。
因此,假设我的自动换行备忘录包含如下信息:
如何将该信息复制到 StringGrid 中?
为了本示例的目的,我制作了一个示例图像来说明结果应该如何:
重要的是要知道,我并不总是知道要使用的列数,例如,如果从文本文件加载备忘录。
也许预定义的列数会更好,例如 5 或 6 列。行数也将是未知的。
我该怎么做?
最佳答案
如果我的理解是对的,那么应该这样做:
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;
关于delphi - 将字符串复制到 StringGrid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9657049/