Best use of MID and INSTR in vb.net

I have a line that looks like this:

"Patient name, document name, patient ID, whatever"

I want to extract each of them and put them in a variable. so var1 will be "Patient Name" var2 will be "Doc name" and so on using instr and mid. what is the best way to do it?

+2


source to share


3 answers


The best way to do it is to use the Split function - here is the vba code to do this:

Dim txt as String = "Patient Name, Doc Name, Patient ID, something else"
Dim x as Variant
Dim i as Long

x = Split(txt, ",")
For i = 0 To UBound(x)
   Debug.Print x(i)
Next i

      



And in VB.Net:

Dim txt as String = "Patient Name, Doc Name, Patient ID, something else"
Dim split As String() = txt.Split(",")
    For Each s As String In  split
        If s.Trim() <> "" Then
            Console.WriteLine(s)
        End If
    Next s

      

+7


source


You should consider using the string methods that are part of the .NET framework instead of the legacy VB functions.



String.Split()

you get 99% of what you want.

+2


source


The only reason to avoid the known methods from Microsoft.VisualBasic.Strings module (like InStr and Mid) might be if you are used to methods from System.String from C # background or if you want to make your solution very portable (so you can run it as well in Mono).

Using these methods can be confusing for C # programmers (because the first character index is 1, not 0), but they do have one big advantage: they exchange parameter comparison settings! You may notice that if you use the standard Compare Binary option, some methods are even faster than their System.String counterparts. This is because, in this case, they perform binary comparisons, while other methods will have to perform culture-sensitive comparisons.

Last but not least, none of these methods will throw exceptions if you pass Nothing (null) to them, because in VB.NET, Nothing is not the empty string equivalent. Microsoft is now demonstrating its intention to drop these features in future releases of the .NET platform (although no one can be sure that someone will survive another version).

Take a look at the wicks and benefits of both the "inherent" string functions in VB.NET and those provided by the System.String class. For a VB.NET programmer with a Visual Basic background, using these "inherent" functions can be a natural way to solve your problems, and you generally don't need to worry about their performance.

+1


source







All Articles