简体   繁体   中英

How to loop through each visible char of a TRichEdit text?

In Delphi 10.3.3, which is the most simple and fastest and most efficient way to loop through each visible Char (ie excluding non-printable characters such as eg #13 ) of a (multiline) TRichEdit text? I then need to get and set the color of each char according to my calculations.

I have tried this one:

function GetCharByIndex(Index: Integer): Char;
begin
  RichEdit1.SelStart := Index;
  RichEdit1.SelLength := 1;
  Result := RichEdit1.SelText[1];
end;

RichLen := RichEdit1.GetTextLen - RichEdit1.Lines.Count;
for i := 0 to RichLen - 1 do
begin
  c := GetCharByIndex(i);
  if c = #13 then CONTINUE;
  // ... do my stuff here
end;

But I am sure there must be a better way.

var
  i: Integer;  
  c: Char;
  cord: Integer;
...
i := -1;
for c in RichEdit1.Text do
begin
  Inc(i);
  cord := ord(c);
  if (cord = 13) then
    Dec(i);
  if (cord >= 32) and (not ((cord > 126) and (cord < 161))) then
  begin
    // do your stuff here, for example exchanging red and green colors:
    RichEdit1.SelStart := i;
    RichEdit1.SelLength := 1;
    if RichEdit1.SelAttributes.Color = clGreen then
      RichEdit1.SelAttributes.Color := clRed
    else if RichEdit1.SelAttributes.Color = clRed then
      RichEdit1.SelAttributes.Color := clGreen;
  end;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM