delphi - Delphi 中的字符串比较

标签 delphi delphi-2009

我有两个字符串,需要比较它们是否相等。

字符串 1 是这样创建的:

var
    inBuf: array[0..IN_BUF_SIZE] of WideChar;
    stringBuilder : TStringBuilder;
    mystring1:string;
    ...
begin

stringBuilder := TStringBuilder.Create;

for i := startOfInterestingPart to endOfInterestingPart do
begin
  stringBuilder.Append(inBuf[i]);
end;

mystring1 := stringBuilder.ToString();
stringBuilder.Free;

字符串 2 是常量字符串 'ABC'

当字符串 1 显示在调试控制台中时,它等于“ABC”。但比较

  1. AnsiCompareText(mystring1, 'ABC')
  2. mystring1 = 'ABC'
  3. CompareStr(mystring1, 'ABC')

所有人都报告不平等。

我想我需要将字符串 2 ('ABC') 转换为与字符串 1 相同的类型。

我怎样才能做到这一点?

2012 年 9 月 26 日更新:

aMessage 在日志输出中显示为 {FDI-MSG-START-Init-FDI-MSG-END}

这是打印字符串长度的代码:

StringToWideChar('{FDI-MSG-START-Init-FDI-MSG-END}', convString, iNewSize);

...

OutputDebugString(PChar('Len (aMessage): ' + IntToStr(Length(aMessage))));
OutputDebugString(PChar('Len (original constant): ' + IntToStr(Length('{FDI-MSG-START-Init-FDI-MSG-END}'))));
OutputDebugString(PChar('Len (convString): ' + IntToStr(Length(convString))));

这是日志输出:

[3580] Len (aMessage): 40
[3580] Len (original constant): 32
[3580] Len (convString): 0

最佳答案

看起来您在有意义的部分之后将垃圾数据保留在宽字符串中,在更新中,Length(aMessage) 返回 40,而源字符串的长度为 32。

在Delphi中,宽字符串与COM BSTR兼容,这意味着它可以容纳空字符,空字符不会终止它,它将其长度保持在字符数据的负偏移量处。其中可能存在的空字符有助于将其转换为其他字符串类型,但不会改变其自身的终止符。

考虑以下因素,

const
  Source = '{FDI-MSG-START-Init-FDI-MSG-END}';
var
  ws: WideString;
  size: Integer;
begin
  size := 40;
  SetLength(ws, size);
  StringToWideChar(Source, PWideChar(ws), size);

  // the below assertion fails when uncommented
//  Assert(CompareStr(Source, ws) = 0);

  ws := PWideChar(ws);  // or SetLength(ws, Length(Source));
  // this assertion does not fail
  Assert(CompareStr(Source, ws) = 0);
end;

关于delphi - Delphi 中的字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12600197/

相关文章:

c# - 本地化与定制

Delphi,如何在两个不同的包中安装同名的组件

delphi - Delphi 2009 中的 Zlib

delphi - 如何在客户端仍处于连接状态时更新 DataSnap 服务器?

Delphi - ListView问题

delphi - 我如何知道何时停止滚动 TScrollBar?

delphi - 数组作为结果类型和函数输入

delphi - Delphi ASIO VST 和 MiniHost 的 Midi 计时问题

delphi - Delphi 2009-如何修复已标识的“未声明的标识符”

delphi - Delphi 2009 图像列表和图像中的 PNG