是否有必要在Delphi中将字符串转换为WideString?

Mar*_*mke 19 delphi string widestring

我找到了一个Windows API函数,它执行字符串的"自然比较".它的定义如下:

int StrCmpLogicalW(
    LPCWSTR psz1,
    LPCWSTR psz2
);
Run Code Online (Sandbox Code Playgroud)

要在Delphi中使用它,我这样说:

interface
  function StrCmpLogicalW(psz1, psz2: PWideChar): integer; stdcall;

implementation
  function StrCmpLogicalW; external 'shlwapi.dll' name 'StrCmpLogicalW';
Run Code Online (Sandbox Code Playgroud)

因为它比较了Unicode字符串,所以当我想比较ANSI字符串时,我不确定如何调用它.似乎足以将字符串转换为WideString然后转换为PWideChar,但是,我不知道这种方法是否正确:

function AnsiNaturalCompareText(const S1, S2: string): integer;
begin
  Result := StrCmpLogicalW(PWideChar(WideString(S1)), PWideChar(WideString(S2)));
end;
Run Code Online (Sandbox Code Playgroud)

我对字符编码知之甚少,所以这就是我提问的原因.这个函数是OK还是我应该首先以某种方式转换两个比较的字符串?

gab*_*abr 11

请记住,将字符串转换为WideString将使用默认系统代码页转换它,这可能是您可能需要的,也可能不是.通常,您希望使用当前用户的区域设置.

来自WCharFromCharSystem.pas:

Result := MultiByteToWideChar(DefaultSystemCodePage, 0, CharSource, SrcBytes,
  WCharDest, DestChars);
Run Code Online (Sandbox Code Playgroud)

您可以通过调用SetMultiByteConversionCodePage来更改DefaultSystemCodePage .


Ian*_*oyd 5

完成任务的更简单方法是将您的函数声明为:

interface
   function StrCmpLogicalW(const sz1, sz2: WideString): Integer; stdcall;

implementation
   function StrCmpLogicalW; external 'shlwapi.dll' name 'StrCmpLogicalW';
Run Code Online (Sandbox Code Playgroud)

因为WideString变量指向a的指针WideChar(以同样的方式AnsiString变量指向AnsiChar.的指针.)

这样Delphi会自动将AnsiString"上转换" WideString为你.

更新

既然我们现在处于世界之中UnicodeString,你就会成功:

interface
   function StrCmpLogicalW(const sz1, sz2: UnicodeString): Integer; stdcall;

implementation
   function StrCmpLogicalW; external 'shlwapi.dll' name 'StrCmpLogicalW';
Run Code Online (Sandbox Code Playgroud)

因为UnicodeString变量仍然是指向\0\0终止字符串的指针WideChars.所以如果你打电话:

var
    s1, s1: AnsiString;
begin
    s1 := 'Hello';
    s2 := 'world';

    nCompare := StrCmpLogicalW(s1, s2);
end;
Run Code Online (Sandbox Code Playgroud)

当您尝试将a传递给一个AnsiString带有a的函数时,UnicodeString编译器将自动MultiByteToWideChar在生成的代码中为您调用.

CompareString支持Windows 7中的数字排序

从Windows 7开始,Microsoft添加SORT_DIGITSASNUMBERSCompareString:

Windows 7:在排序期间将数字视为数字,例如,在"10"之前排序"2".

这些都没有帮助回答实际问题,这个问题涉及何时必须转换或转换字符串.