Delphi中的字符串比较
我有两个字符串,我需要比较它们是否相等 字符串1是这样创建的:Delphi中的字符串比较,delphi,delphi-2009,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 endOfInterestingPar
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')
'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;
1) 我的字符串长度是多少?2) 如果长度相同-创建一个循环,逐字符,哪个字符相同,什么时候不同。3) 如果/当发现不同的字符时,比较两个字符串的单词(字符)。我想您确实理解“ABC”和“АС”没有单一的公共字母。请将字符串2(“ABC”)转换为与字符串1相同的类型——我认为这没有必要,但如果您坚持的话——var mystring1,mystring2:string。。。mystring2:=“ABC”;AnsiCompareText(一个消息,ABC)你比较什么?aMessage或mystring1???aMessage等于mystring1。抱歉打错了。现在发生了一件奇怪的事。在一台机器上,
AnsiCompareText(mystring1,'ABC')
报告相等,在另一台机器上不报告相等。在这两种情况下,mystring1都是从C#应用程序接收的(在这两台机器上,C#应用程序都在Visual Studio 10中运行)。只有操作系统不同——在工作的机器上,是Windows 7;在另一台机器上(不工作的机器上),是Windows XP Professional,2002版,Service Pack 3。