gpt4 book ai didi

delphi - 在delphi中获取字符串字节长度

转载 作者:行者123 更新时间:2023-12-03 18:10:01 27 4
gpt4 key购买 nike

我想找到字符串字节长度。首先转换为字节,然后获取长度,那么如何获取字符串字节长度?

var
val : String;
begin
val:= 'example';
ShowMessage(IntToStr(Length(val) * ???)); -> BYTE LENGTH
end;

最佳答案

您可以使用 SysUtils.ByteLength() 功能:

uses
SysUtils;

var
val : String;
begin
val:= 'example';
ShowMessage(IntToStr(ByteLength(val)));
end;

只知道 ByteLength()只接受 UnicodeString作为输入,所以任何传递给它的字符串,无论是 (Ansi|Wide|UTF8|RawByte|Unicode)String , 将被转换为 UTF-16(如果还没有),然后它将返回 UTF-16 中的字节数,就像 Length(val) * SizeOf(WideChar) .

如果你想要 UnicodeString 的字节长度在另一个字符集中,您可以使用 SysUtils.TEncoding 类:
var
val : String;
begin
val := 'example';
ShowMessage(IntToStr(TEncoding.UTF8.GetByteCount(val)));
end;
var
val : String;
enc : TEncoding;
begin
val := 'example';
enc := TEncoding.GetEncoding(...); // codepage number or charset name
try
ShowMessage(IntToStr(enc.GetByteCount(val)));
finally
enc.Free;
end;
end;

或者,您可以使用 AnsiString(N)类型以转换 UnicodeString到特定的代码页,然后使用 Length()不管是什么 N 都可以得到它的字节长度实际上是:
type
Latin1String = type AnsiString(28591); // can be any codepage supported by the OS...
var
val : String;
val2: Latin1String;
begin
val := 'example';
val2 := Latin1String(val);
ShowMessage(IntToStr(Length(val2)));
end;

关于delphi - 在delphi中获取字符串字节长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29364461/

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