我想将备忘录的内容复制到TStringGrid.
如果字符串之间存在空格或间隙,则应将该字添加到StringGrid中的单元格中.
所以,假设我的Wordwrapped Memo包含一些信息:

我怎么能将这些信息复制到StringGrid?
出于这个例子的目的,我制作了一个示例Image来说明结果应该如何:

重要的是要知道我不会总是知道要使用的列数,例如,如果从文本文件加载备忘录.
也许预定数量的列会更好,例如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;
Run Code Online (Sandbox Code Playgroud)
截图http://privat.rejbrand.se/stringgridwordsfrommemo.png
TokenizerRTL中有一个(由David评论过).它会使用您选择的分隔符将文本拆分为单词.
这个例子来自Olaf Moinen在Zarko Gaijic撰写的一篇文章中的评论:how-to-split-a-delphi-string-to-words-tokens.htm.
uses HTTPUtil;
procedure TForm1.Button1Click(Sender: TObject);
var
LTokenizer: IStringTokenizer;
begin
Memo1.Clear;
LTokenizer := StringTokenizer(Edit1.Text, ' ');
while LTokenizer.hasMoreTokens do
Memo1.Lines.Add(LTokenizer.nextToken);
end;
Run Code Online (Sandbox Code Playgroud)
它将从编辑控件中获取文本并将其放入备忘录中.我将把它作为练习从备忘录到字符串格式做同样的事情.