遍历 UTF8String

Loop through UTF8String

如何迭代UTF8String中的单个字符?我需要打印出单个字符而不是字节..

program Project3;

uses
  System.SysUtils;

var
  Str: UTF8String;
  I: Integer;
begin
  Str := 'Декат';
  for I := 0 to Length(Str) do
  WriteLn(Str[I]);
  ReadLn;
end.

这是一个工作演示:

program Project11;

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

function GetNextChar(const S: UTF8String; N: Integer): Integer;
var
  B: Byte;

begin
  if N > Length(S) then begin
    Result:= -1;
    Exit;
  end;
  B:= Byte(S[N]);
  if (B and  = 0 ) then
    Result:= N + 1
  else if (B and $E0 = $C0) then
    Result:= N + 2
  else if (B and $F0 = $E0) then
    Result:= N + 3
  else if (B and $F8 = $F0) then
    Result:= N + 4
  else
    Result:= -1; // invalid code
end;

procedure Test;
var
  S: UTF8String;
  S1: UTF8String;
  N, M: Integer;

begin
  S:= 'Декат';
  N:= 1;
  SetConsoleOutputCP(CP_UTF8);
  Writeln(S);
  while True do begin
    M:= GetNextChar(S, N);
    if M < 0 then Break;
    S1:= Copy(S, N, M - N);
    Writeln(N, ':  ', S1);
    N:= M;
  end;
end;

begin
  try
    Readln; // Select consolas font here
    Test;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.