2012-02-29 113 views
-1

我得到這個部分代碼:爲什麼這個字符串比較不起作用?

var 
    MYOBCardId, WSCustCode, ExCode, 
    Destination, IncomeStream, MyobSalesAc: String; 

IncomeStream := VarToStr(Trim(SheetData.Cells[7, StrRow])); 
MyobSalesAc := ''; 
if IncomeStream = '840 DRUG-temp controlled' then 
    MyobSalesAc := '42400'; 
if AnsiCompareStr(IncomeStream,'900 Industrial') = 0 then 
    MyobSalesAc := '41200'; 
if IncomeStream = '950 Live Animals' then 
    MyobSalesAc := '41800'; 

的事情是,如果再聲明似乎並沒有工作。如果IncomeStream的值是'900 Industrial'(通過調試器檢查),MYOBSalesAc將是''而不是'41200'。 比較完全不起作用。它對所有的值都是一樣的。使用AnsiComparestr不會給出正確的結果。

任何指針?

問候 拉希德

+0

'IncomeStream'是不是你說的樣子。已知'AnsiCompareStr'工作正常。 – 2012-02-29 14:50:27

+0

我試着使用IncomeStream ='900 Industrial',其中IncomeStream ='900 Industrial'。如果它是真的,結果是錯誤的。 – mra 2012-02-29 14:54:35

+0

'='運算符也可以正常工作。 – 2012-02-29 14:55:21

回答

4

AnsiCompareStr,等號比較運算符=是所有已知的正常工作。因此,我們只能得出結論,IncomeStream不具有值'900 Industrial'。最明顯的可能是該空間實際上是一些其他形式的空白。也許是製表符。或者也許是一個不間斷的空間。或者也許是兩個空格。

看看這兩個字符串的二進制表示並進行比較。

+0

感謝大衛,但是你在二進制表示中丟失了我的位置,請提前致謝 – mra 2012-02-29 15:03:16

+0

查看'ord(IncomeStream [4])的值'在調試器中,如果它是一個空格,那麼它將會是32. – 2012-02-29 15:06:14

+0

它返回一個32.因此需要刪除空格,謝謝 – mra 2012-02-29 15:25:10

0

對於這種文本比較,最好使用AnsiSameText。 AnsiSameText將進行不區分大小寫的比較。爲區分大小寫比較,請改用AnsiSameStr。如果您使用的是D2009或更高版本,則必須使用SameText和SameStr。

+0

ansi delphis上的SameText和SameStr有什麼問題? – 2012-02-29 18:27:14

+3

可悲的是,克里斯托弗你錯了。 Ansi以一個功能的名義應該在一個理智的世界裏,這意味着它只是Ansi字符串的一個函數,但由於各種歷史原因,這並不意味着在Delphi中。仔細閱讀文檔,觀察混亂。 – 2012-02-29 19:03:28

+1

在2009年之前的Delphi中,SameText和SameStr無法使用ASCII [link](http://en.wikipedia.org/wiki/ASCII)字符。在Delphi7上試試這個代碼:「如果SameText('español','ESPAÑOL')...」,你會承擔我說的。 – 2012-02-29 19:24:07

0

要找出差異在哪裏,請使用您自己的比較功能。逐個角色地去角色,直到你發現你的眼睛看起來相同,但是序數值不同。

其他人建議使用調試器,但如果你不能這樣做,那麼編寫代碼。

function CompareStrExt(s1,s2:String; var idx:Integer; var c1,c2:Char):Boolean; 
var 
len1,len2,minlen:Integer; 
begin 
    result := true; 
    c1 := Chr(0); 
    c2 := Chr(0); 
    idx := 1; 
    len1 := Length(s1); 
    len2 := Length(s2); 
    minlen := len1; 
    if len2<minlen then 
     minlen := len2; 
    while idx <= minlen do begin 
     c1 := s1[idx]; 
     c2 := s2[idx]; 
     if c1<>c2 then begin 
      result := false; 
      exit; 
     end; 
     Inc(idx); 
    end; 
    if idx>len1 then 
     c1 := Chr(0) 
    else 
     c1 := s1[idx]; 

    if idx>len2 then 
     c2 := Chr(0) 
    else 
     c2 := s2[idx]; 

    result := (len1=len2); 



end; 

下面是一個示例調用:

if not CompareStrExt('123','123a',idx,c1,c2) then begin 
     // make ordinal Numeric (binary) values visible to your eyeballs. 
     msg := IntToStr(Ord(c1)) + ' <> ' + IntToStr(Ord(c2)); 
    end; 
相關問題