C# 如何在c中使用VB6 InStr IntStRev和Mid#

C# 如何在c中使用VB6 InStr IntStRev和Mid#,c#,C#,我曾在一个项目中使用VB6,后来我切换到c,我的VB6代码中有一个函数,我想在我的c项目中使用 子字符串可能可以做到这一点 这是我的VB6代码 position = InStr(1, strout, "4000072") If position > 0 Then position2 = InStrRev(strout, "0000", position) strout = Mid$(strout, position2 - 512, 512) End If 就你而言: p

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


子字符串可能可以做到这一点

这是我的VB6代码

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

If position > 0 Then
    position2 = InStrRev(strout, "0000", position)
    strout = Mid$(strout, position2 - 512, 512)
End If
就你而言:

position = InStr(1, strout, "4000072")
If position > 0 Then
    position2 = InStrRev(strout, "0000", position)
    strout = Mid$(strout, position2 - 512, 512)
  • InStr(1,干草堆,针)
    中的
    1
    表示“从头开始”,它是不必要的,所以可以修改。注:在.NET(VB.NET和C#)中,字符串索引从
    0
    开始,而不是从
    1
    开始
  • Mid$
    结尾处的
    $
    是从20世纪80年代VB早期遗留下来的一个古老版本,即使在VB6中也没有必要。您的
    If
    也缺少其
    End If
因此:


“String.Substring可能可以做到这一点。”-是的。与
IndexOf
LastIndexOf
一起使用。如果您能找到这些函数的替代品,请继续使用这些函数。添加对Microsoft.VisualBasic的引用,使用vb6=Microsoft.VisualBasic.Strings添加;到文件顶部,现在您可以编写vb6.InStr等@HansPassant当他们想到使用它的代码时,我是唯一一个想呕吐的人吗?那为什么还要学C呢。@Ashigore有很多遗留代码,不值得用C重新编写。最好将其保存在VB.NET imo中。为什么index400>-1而不是index400>0是这种新逻辑?请注意,您的C#等价物并不完全相同,因此不要盲目地替换它们。例如,如果start+length超出字符串的末尾,则子字符串将抛出,而Mid将允许这样做。如果您想要相同的行为,可以使用Microsoft.VisualBasic.Strings类(在.NET Core BTW中不可用)中的方法,或者更可能的是,滚动您自己的C#版本。@AmanAli
IndexOf
在未找到字符串时返回
-1
,在开头(位置0)找到字符串时返回
0
@Joe我已经修改了我的代码,以便更好地模仿Mid的行为。@Dai修改后的代码有错误,请检查其每个变量的名称是否不同,但没有定义。
position = InStr(1, strout, "4000072")
If position > 0 Then
    position2 = InStrRev(strout, "0000", position)
    strout = Mid$(strout, position2 - 512, 512)
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 );
}