0

我正在制作应用程序来替换两种非常相似的语言的不同单词。按时间计算的单词数可能至少会达到 10.000+。单词没有太大差异,几乎是相同的语言,但是存在差异。

所以,我设法以足够快的速度替换备忘录中的单词,但我不知道如何选择备忘录中的所有替换单词,以便可以看到哪些单词被替换了。这可能吗?

这是单词的替换方式:

procedure TForm1.TranslateExecute(Sender: TObject);
var i: integer;
    S, OldPattern, NewPattern: string;
begin
  S:= Memo1.Lines.Text;

  for i := 0 to (StrListV.Count - 1) do  {StrListV is created earlier, contains words that should be replaced}
  begin        
    OldPattern:= StrListV.Strings[i];
    NewPattern:= StrListV1.Strings[i]; {StrListV1 contains new words}
    S:= FastStringReplace(S, OldPattern, NewPattern,[rfReplaceAll]);
  end;

  Memo1.BeginUpdate;
  Memo1.Clear;
  Memo1.Lines.Text:= S;
  Memo1.EndUpdate;
end;
4

1 回答 1

3

既不也不TMemo支持TRichEdit多项选择,因此您实际上无法突出显示已替换的单词。但是使用TRichEdit,您可以做的是更改您替换的单词的前景色/背景色。

TRichEdit有一个返回搜索字符串索引的FindText()方法(包装EM_FINDTEXT消息)。循环调用它,或者您可以选择每个找到的单词,设置它的颜色,然后用新文本替换它。重复直到FindText()找不到更多匹配项。

尝试这样的事情:

uses
  RichEdit, CommDlg;

procedure TForm1.TranslateExecute(Sender: TObject);
var
  I, Pos: Integer;
  EventMask: LRESULT;
  OldPattern, NewPattern: string;
  Find: RichEdit.FINDTEXT;
  Rng: RichEdit.CHARRANGE;
  Fmt: RichEdit.CHARFORMAT2;
begin
  EventMask := SendMessage(RichEdit1.Handle, EM_SETEVENTMASK, 0, 0);
  RichEdit1.Lines.BeginUpdate;
  try
    for I := 0 to StrListV.Count - 1 do
    begin        
      OldPattern := StrListV.Strings[I];
      NewPattern := StrListV1.Strings[I];
      Pos := 0;
      repeat
        Find.chrg.cpMin := Pos;
        Find.chrg.cpMax := -1;
        Find.lpstrText := PChar(OldPattern);
        Pos := SendMessage(RichEdit1.Handle, EM_FINDTEXT, FR_DOWN or FR_WHOLEWORD, LPARAM(@Find));
        if Pos = -1 then Break;

        Rng.cpMin := Pos;
        Rng.cpMax := Pos + Length(OldPattern);

        ZeroMemory(@Fmt, SizeOf(Fmt));
        Fmt.cbSize := SizeOf(Fmt);
        Fmt.dwMask := CFM_COLOR or CFM_BACKCOLOR;
        Fmt.crTextColor := ColorToRGB(clHighlightText);
        Fmt.crBackColor := ColorToRGB(clHighlight);

        SendMessage(RichEdit1.Handle, EM_EXSETSEL, 0, LPARAM(@Rng));
        SendMessage(RichEdit1.Handle, EM_SETCHARFORMAT, SCF_SELECTION, LPARAM(@Fmt));
        SendMessage(RichEdit1.Handle, EM_REPLACESEL, 0, LPARAM(PChar(NewPattern)));

        Inc(Pos, Length(NewPattern));
      until False;
    end;
  finally
    RichEdit1.Lines.EndUpdate;
    SendMessage(RichEdit1.Handle, EM_SETEVENTMASK, 0, EventMask);
  end;
end;
于 2015-05-19T17:57:08.917 回答