如何使固定长度的 Delphi 字符串使用宽字符?

发布于 2024-10-14 11:59:48 字数 796 浏览 10 评论 0原文

在 Delphi 2010 下(也可能在 D2009 下),默认字符串类型是 UnicodeString。

但是,如果我们声明...

const
 s  :string = 'Test';
 ss :string[4] = 'Test';

...则第一个字符串 s 声明为 UnicodeString,但第二个字符串 ss 声明为 <强>AnsiString!

我们可以检查一下: SizeOf(s[1]); 将返回大小 2 和 SizeOf(ss[1]);将返回大小 1。

如果我声明...

var
  s  :string;
  ss :string[4];

...比我希望 ss 也是 UnicodeString 类型。

  1. 我如何告诉 Delphi 2010 这两个字符串都应该是 UnicodeString 类型?
  2. 我还能如何声明 ss 拥有四个 WideChar?编译器不会接受类型声明 WideString[4]UnicodeString[4]
  3. 对于同一个类型名称:字符串,两个不同编译器声明的目的是什么?

Under Delphi 2010 (and probably under D2009 also) the default string type is UnicodeString.

However if we declare...

const
 s  :string = 'Test';
 ss :string[4] = 'Test';

... then the first string s if declared as UnicodeString, but the second one ss is declared as AnsiString!

We can check this: SizeOf(s[1]); will return size 2 and SizeOf(ss[1]); will return size 1.

If I declare...

var
  s  :string;
  ss :string[4];

... than I want that ss is also UnicodeString type.

  1. How can I tell to Delphi 2010 that both strings should be UnicodeString type?
  2. How else can I declare that ss holds four WideChars? The compiler will not accept the type declarations WideString[4] or UnicodeString[4].
  3. What is the purpose of two different compiler declarations for the same type name: string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱人如己 2024-10-21 11:59:48

答案在于,string[n](一种 ShortString)现在被视为遗留类型。 Embarcadero 决定不将 ShortString 转换为支持 Unicode。由于引入了长字符串,如果我没记错的话,在 Delphi 2 中,这对我来说似乎是一个合理的决定。

如果您确实想要固定长度的 WideChar 数组,那么您可以简单地声明 array [1..n] of char

The answer to this lies in the fact that string[n], which is a ShortString, is now considered a legacy type. Embarcadero took the decision not to convert ShortString to have support for Unicode. Since the long string was introduced, if my memory serves correctly, in Delphi 2, that seems a reasonable decision to me.

If you really want fixed length arrays of WideChar then you can simply declare array [1..n] of char.

桃气十足 2024-10-21 11:59:48
  1. 你不能,使用string[4]作为类型。以这种方式声明它会自动使其成为 ShortString。

  2. 将其声明为 Char 数组,这将使其成为 4 个 WideChar 的数组。

  3. 因为string[4]使其成为包含4个字符的字符串。然而,由于 WideChars 的大小可能超过一个字节,因此这会 a) 错误,b) 令人困惑。为了向后兼容,ShortString 仍然存在,并且自动成为 AnsiString,因为它们由 [x] 个单字节字符组成。

  1. You can't, using string[4] as the type. Declaring it that way automatically makes it a ShortString.

  2. Declare it as an array of Char instead, which will make it an array of 4 WideChars.

  3. Because a string[4] makes it a string containing 4 characters. However, since WideChars can be more than one byte in size, this would be a) wrong, and b) confusing. ShortStrings are still around for backward compatibility, and are automatically AnsiStrings because they consist of [x] one byte chars.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文