3
如果脱字符直接相邻或在备忘录中的单词中,我需要能够选择TMemo的整个单词。德尔福 - 获取脱字符在备忘录中的整个单词
考虑以下(其中,|是脱字符号)
Here is some text|
=选择text
Here is so|me text
=选择some
|Here is some text
=选择Here
Here is some text |
=选择 ''
如果脱字符直接相邻或在备忘录中的单词中,我需要能够选择TMemo的整个单词。德尔福 - 获取脱字符在备忘录中的整个单词
考虑以下(其中,|是脱字符号)
Here is some text|
=选择text
Here is so|me text
=选择some
|Here is some text
=选择Here
Here is some text |
=选择 ''
用注释检查这段代码以解释工作原理。
function SelectWordUnderCaret(AMemo:TMemo):string;
var
Line : Integer;
Column : Integer;
LineText: string;
InitPos : Integer;
EndPos : Integer;
begin
//Get the caret position
Line := AMemo.Perform(EM_LINEFROMCHAR,AMemo.SelStart, 0) ;
Column := AMemo.SelStart - AMemo.Perform(EM_LINEINDEX, Line, 0) ;
//Validate the line number
if AMemo.Lines.Count-1 < Line then Exit;
//Get the text of the line
LineText := AMemo.Lines[Line];
Inc(Column);
InitPos := Column;
//search the initial position using the space symbol as separator
while (InitPos > 0) and (LineText[InitPos] <> ' ') do Dec(InitPos);
Inc(Column);
EndPos := Column;
//search the final position using the space symbol as separator
while (EndPos <= Length(LineText)) and (LineText[EndPos] <> ' ') do Inc(EndPos);
//Get the text
Result := Trim(Copy(LineText, InitPos, EndPos - InitPos));
//Finally select the text in the Memo
AMemo.SelStart := AMemo.Perform(EM_LINEINDEX, Line, 0)+InitPos;
AMemo.SelLength := Length(Result);
end;
,你可以使用这样
procedure TForm1.Button1Click(Sender: TObject);
begin
Caption := SelectWordUnderCaret(Memo1) ;
end;
要获得插入符位置,你可以使用AMemo.CaretPos – SimaWB 2011-06-14 06:18:58
+1。该算法对于实际使用非常有用,也就是说,如果您真的想将其用于TMemo:它只会读取所需的文本行,而不是像我一样读取整个备忘录。它可能启用了unicode,因为它测试空白,这是OP需要考虑的事情(什么构成一个词?)。 – 2011-06-14 07:05:18
辉煌,感谢RRUZ。我有一个类似Cosmins,但这看起来更有效率。 – Simon 2011-06-14 07:52:53