delphi - 将字符串复制到 StringGrid?

标签 delphi delphi-xe

我想将备忘录的内容复制到 TStringGrid。

如果字符串之间有空格或间隙,则应将该单词添加到 StringGrid 中其自己的单元格中。

因此,假设我的自动换行备忘录包含如下信息:

enter image description here

如何将该信息复制到 StringGrid 中?

为了本示例的目的,我制作了一个示例图像来说明结果应该如何:

enter image description here

重要的是要知道,我并不总是知道要使用的列数,例如,如果从文本文件加载备忘录。

也许预定义的列数会更好,例如 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;

Screenshot

关于delphi - 将字符串复制到 StringGrid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9657049/

相关文章:

delphi - 在德尔福插入排序算法中找不到简单的错误

德尔福: Char value for newline

delphi - TeeChart TLineSeries - 是否可以为每个系列绘制多条线?

delphi - 如何重新编译对VCL源文件(Menus.pas)的修改?

delphi - 直接使用 GDI+ 在 TeeChart 上绘图

delphi - 如何检测接口(interface)和实现uses子句中无用的Delphi单元?

delphi - 使用接口(interface)时出现内存泄漏问题?

delphi - 在运行时插入控件集非常慢

multithreading - 使用 WaitForMultipleObjects 等待多个线程

delphi - 泛型和 As Cast 的问题