我有两个字符串,需要比较它们是否相等。
字符串 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”。但比较
AnsiCompareText(mystring1, 'ABC')
mystring1 = 'ABC'
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/