1

I need to convert some of the legacy code which is currently in VB6 into C#. I am not able to understand this piece of code. Especially the InStr function, could someone please help me out with this and suggest me it's C# equivalent.

For i = 1 To Len(sString)
sChar = Mid$(sString, i, 1)
iPos = InStr(1, "0123456789", sChar, vbBinaryCompare)
If iPos > 0 Then
sRetStr = sRetStr & sChar
End If
Next i
Sid
  • 141
  • 3
  • 13
  • 1
    [InStr Function (Visual Basic)](https://msdn.microsoft.com/en-us/library/8460tsh1(v=vs.90).aspx) – Ňɏssa Pøngjǣrdenlarp Jun 02 '15 at 17:27
  • If you have access to Microsoft Office, then in something like Excel, Word, or Access, you can use VBA to help figure out VB6 code. (See http://stackoverflow.com/questions/993300/difference-between-visual-basic-and-vba) – rskar Jun 02 '15 at 18:35

2 Answers2

4

The InStr finds the (one-based) index of a string in another string. The closest equivalent in the modern .Net string methods is .IndexOf. However, I would replace the code you have with this C# statement.

string sRetStr = (sString.Where((c) => char.IsDigit(c)).ToArray()).ToString();
Blackwood
  • 4,504
  • 16
  • 32
  • 41
4

I'd pare that code down to this:

sRetStr = Regex.Replace(sSTring, "[^0-9]", "");
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794