gpt4 book ai didi

delphi - 将UnicodeString的char pos转换为utf8字符串中的字节pos

转载 作者:行者123 更新时间:2023-12-03 19:33:39 25 4
gpt4 key购买 nike

我使用Scintilla并将其编码设置为utf8(如果我正确理解的话,这是使其与Unicode字符兼容的唯一方法)。通过这种设置,当谈论文本中的位置时,Scintilla表示字节位置。

问题是,我在程序的其余部分中使用了UnicodeString,并且当我需要在Scintilla编辑器中选择特定范围时,我需要将UnicodeString的字符转换为utf8字符串中与UnicodeString对应的字节pos。 。我如何轻松做到这一点?谢谢。

PS,当我找到ByteToCharIndex时,我认为这是我的需要,但是根据其文档和测试结果,该方法仅在系统使用多字节字符系统(MBCS)的情况下有效。

最佳答案

您应该使用UTF8 description自己解析UTF8字符串。我编写了ByteToCharIndex的快速UTF8类似物并在西里尔字母字符串上进行了测试:

function UTF8PosToCharIndex(const S: UTF8String; Index: Integer): Integer;
var
I: Integer;
P: PAnsiChar;

begin
Result:= 0;
if (Index <= 0) or (Index > Length(S)) then Exit;
I:= 1;
P:= PAnsiChar(S);
while I <= Index do begin
if Ord(P^) and $C0 <> $80 then Inc(Result);
Inc(I);
Inc(P);
end;
end;

const TestStr: UTF8String = 'abФЫВА';

procedure TForm1.Button2Click(Sender: TObject);
begin
ShowMessage(IntToStr(UTF8PosToCharIndex(TestStr, 1))); // a = 1
ShowMessage(IntToStr(UTF8PosToCharIndex(TestStr, 2))); // b = 2
ShowMessage(IntToStr(UTF8PosToCharIndex(TestStr, 3))); // Ф = 3
ShowMessage(IntToStr(UTF8PosToCharIndex(TestStr, 5))); // Ы = 4
ShowMessage(IntToStr(UTF8PosToCharIndex(TestStr, 7))); // В = 5
end;




反向功能也没有问题:

function CharIndexToUTF8Pos(const S: UTF8String; Index: Integer): Integer;
var
P: PAnsiChar;

begin
Result:= 0;
P:= PAnsiChar(S);
while (Result < Length(S)) and (Index > 0) do begin
Inc(Result);
if Ord(P^) and $C0 <> $80 then Dec(Index);
Inc(P);
end;
if Index <> 0 then Result:= 0; // char index not found
end;

关于delphi - 将UnicodeString的char pos转换为utf8字符串中的字节pos,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10386054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com