首页 > 解决方案 > 如何在 c# 中使用 VB6 InStr IntStRev 和 Mid

问题描述

我在一个项目中使用了 VB6,后来我切换到 c# 我在我的 VB6 代码中有一个函数,我想在我的 C# 项目中使用。

String.Substring 也许可以做到这一点。

这是我的 VB6 代码。

position = InStr(1, strout, "4000072")

If position > 0 Then
    position2 = InStrRev(strout, "0000", position)
    strout = Mid$(strout, position2 - 512, 512)
End If

标签: c#

解决方案


VB6: index = InStr( haystack, needle )
C# : index = haystack.IndexOf( needle );

VB6: index = InStrRev( haystack, needle )
C# : index = haystack.LastIndexOf( needle );

VB6: substring = Mid( largerString, start, length )
C# : substring = largerString.Substring( start, length );

在你的情况下:

position = InStr(1, strout, "4000072")
If position > 0 Then
    position2 = InStrRev(strout, "0000", position)
    strout = Mid$(strout, position2 - 512, 512)
  • 1in表示“InStr( 1, haystack, needle )从头开始”,没有必要,可以省略。注意 .NET(VB.NET 和 C#)中的字符串索引从 .NET 开始0而不是1.
  • $结尾Mid$是 1980 年代早期 VB 的古老保留,即使在 VB6 中也没有必要。你If也错过了它的End If.

所以:

Int32 index400 = strout.IndexOf( "4000072" );
if( index400 > -1 ) {
    index000 = strout.LastIndexOf( "00000", index400 );

    Int32 start = Math.Max( index0000 - 512, 0 );
    Int32 length = Math.Min( 512, index0000.Length - start );  
    strout = strout.Substring( start, length );
}

推荐阅读