2015-09-07 31 views
0

我正在努力将一些旧的VB6代码迁移到C#此刻,我一直在测试我的C#代码对VB代码以检查每种语言中的对应方法返回相同的价值。InStr在使用空字符串时返回1

我有问题这个if语句:

If InStr(1, "LPTVJY", strTempTaxCode) <> 0 Then 
    strTempTaxCode = "0" & strTempTaxCode 
End if 

strTtempTaxCode = ""价值1InStr(1, "LPTVJY", strTempTaxCode)调用返回。为什么是这样?据我所知,我应该返回0因为从"LPTVJY"字符都不在strTempTaxCode

回答

0

在VB中,字符串是1基于。正因为如此,省略时,为开始(起始位置,从搜索)的默认值是1。

字符串2(你搜索一个)的长度为零或无,InStr返回启动* 1),这是在外壳1

* 1)MSDN documentation on InStr

因为没有字符从"LPTVJY"短语strTempTaxCode建议你曲解功能。它在string1中搜索string2。文档中提到了很多边缘案例以及这种情况下函数返回的内容。但是,该函数可能比这更简单,并且可以编写为嵌套循环,大致如下(仅在内部进行更加优化的方式)。

For s = start to Len(string1) - start 
    For c = 1 to Len(string2) 

    ' Out of characters. There is no match. 
    If c+s-1 > Len(string1) then Return 0 

    ' Mismatch. Try again for the next value of 's'. 
    If SubStr(string1, c+s-1) <> SubStr(string2, c) then Exit For 

    Next 
Next 

' If you get here, a match is found at position s. 
Return s 

请把上面的代码当作伪代码来处理。这仅仅是为了解释,我不知道它是否真的有效。

1

全部非零长度的字符串(包括单字符字符串)包含空字符串。

Debug.Print InStr("abc", "")  ' => 1 
Debug.Print InStr("a", "")  ' => 1 
Debug.Print "abc" & "" = "abc" ' => True 

如果你有麻烦缠绕的概念你的头,认为所有的数字都为1的系数:

' (not a real function) 
Debug.Print Factors(2)   ' => 1, 2 
Debug.Print 2 * 1 = 2   ' => True 

这就是所谓的乘标识属性。您可以将字符串视为具有涉及空字符串的类似身份属性。

如果你不想做InStr()为空字符串匹配,做了初步的测试调用前:

If Len(strTempTaxCode) > 0 Then 
    If InStr(1, "LPTVJY", strTempTaxCode) <> 0 Then 
     strTempTaxCode = "0" & strTempTaxCode 
    End If 
End If