如何使固定长度的 Delphi 字符串使用宽字符?
在 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 类型。
- 我如何告诉 Delphi 2010 这两个字符串都应该是 UnicodeString 类型?
- 我还能如何声明 ss 拥有四个 WideChar?编译器不会接受类型声明
WideString[4]
或UnicodeString[4]
。 - 对于同一个类型名称:字符串,两个不同编译器声明的目的是什么?
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.
- How can I tell to Delphi 2010 that both strings should be UnicodeString type?
- How else can I declare that ss holds four WideChars? The compiler will not accept the type declarations
WideString[4]
orUnicodeString[4]
. - What is the purpose of two different compiler declarations for the same type name: string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案在于,
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 aShortString
, is now considered a legacy type. Embarcadero took the decision not to convertShortString
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
.你不能,使用
string[4]
作为类型。以这种方式声明它会自动使其成为 ShortString。将其声明为 Char 数组,这将使其成为 4 个 WideChar 的数组。
因为
string[4]
使其成为包含4个字符的字符串。然而,由于 WideChars 的大小可能超过一个字节,因此这会 a) 错误,b) 令人困惑。为了向后兼容,ShortString 仍然存在,并且自动成为 AnsiString,因为它们由 [x] 个单字节字符组成。You can't, using
string[4]
as the type. Declaring it that way automatically makes it a ShortString.Declare it as an array of Char instead, which will make it an array of 4 WideChars.
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.