2012-09-26 13 views
3

我有兩個字符串,我需要比較兩個字符串是否相等。Delphi中的字符串比較

串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 
+0

1)什麼是mystring.length? 2)如果長度相同 - 做一個循環,通過字符char,哪些字符是相同的,什麼時候是不同的。 3)如果/當發現不同的字符時,比較兩個字符串的Word(char)。 我猜你明白「ABC」和「АВС」沒有單一的普通字母。 –

+0

*將字符串2('ABC')轉換爲與字符串1 *相同的類型 - 我在此看不需要,但是如果您堅持 - * var mystring1,mystring2:string; ... mystring2:='ABC'; * –

+0

* AnsiCompareText(aMessage,'ABC')*你有什麼比較? aMessage或mystring1? –

回答

2

它看起來像你的有意義的部分後,保持在你的寬字符串垃圾數據,在您的更新,Length(aMessage)返回40,而源字符串的長度爲32

在Delphi寬字符串是COM BSTR兼容,這意味着它可以包含空字符,null不會終止它,它將其長度保持在字符數據的負偏移處。可能的空字符有助於將其轉換爲其他字符串類型,但不會改變其自身的終止。

考慮下面的,

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;