是否需要在Delphi中将字符串转换为WideString? [英] Is it necessary to convert string to WideString in Delphi?
问题描述
我发现一个Windows API函数执行字符串的自然比较。它定义如下:
I found a Windows API function that performs "natural comparison" of strings. It is defined as follows:
int StrCmpLogicalW(
LPCWSTR psz1,
LPCWSTR psz2
);
要在Delphi中使用它,我以这种方式宣布:
To use it in Delp I declared it this way:
interface
function StrCmpLogicalW(psz1, psz2: PWideChar): integer; stdcall;
implementation
function StrCmpLogicalW; external 'shlwapi.dll' name 'StrCmpLogicalW';
因为它比较了 Unicode 字符串,当我想比较ANSI字符串时,我不知道如何调用它。似乎足以将字符串转发到WideString,然后到FlideChar,但是我不知道这种方法是否正确:
Because it compares Unicode strings, I'm not sure how to call it when I want to compare ANSI strings. It seems to be enough to cast strings to WideString and then to PWideChar, however, I have no idea whether this approach is correct:
function AnsiNaturalCompareText(const S1, S2: string): integer;
begin
Result := StrCmpLogicalW(PWideChar(WideString(S1)), PWideChar(WideString(S2)));
end;
我对字符编码知之甚少,这是我问题的原因。这个函数是否正常,或者我应该首先将比较的字符串转换为某种方式?
I know very little about character encoding so this is the reason of my question. Is this function OK or should I first convert both the compared strings somehow?
推荐答案
请记住,将一个字符串转换为WideString将使用默认的系统代码页进行转换,这可能或可能不是您需要的。通常情况下,您需要使用当前用户的区域设置。
Keep in mind that casting a string to a WideString will convert it using default system codepage which may or may not be what you need. Typically, you'd want to use current user's locale.
从 System.pas中的WCharFromChar
:
Result := MultiByteToWideChar(DefaultSystemCodePage, 0, CharSource, SrcBytes,
WCharDest, DestChars);
您可以通过调用 SetMultiByteConversionCodePage 。
这篇关于是否需要在Delphi中将字符串转换为WideString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!