skmasq
skmasq

Reputation: 4521

VB.NET string.replace() isn't always working as expected

Data examples:

What I need extract from these:

Is this the correct way to extract?
String.Split(" || ")(0)

The problem is, sometimes I get these values saved to Database:

I just want to know which way is the correct one so I can change every line to the correct one.

Upvotes: 3

Views: 203

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460340

No, there is no overload that accepts a string. So you are actually using the overload of String.Split which accepts a ParamArray Char(). But this will check if any of these chars match, so not only if the whole sub-string matches. It is the same as this:

 Dim first = text.Split(" "c, "|"c, "|"c, " "c)(0) ' "EFT-"

Use this instead:

Dim first = text.Split({" || "}, StringSplitOptions.RemoveEmptyEntries)(0)

Note that you can also use StringSplitOptions.None, that's not the problem.

String.Split Method(String(), StringSplitOptions)

Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. A parameter specifies whether to return empty array elements.

But note that you should set OPTION STRICT to on, then your code would not even compile since a string is not a Char() implicitly. With OPTION STRICT off it will be converted silently.

Option Strict on by default in VB.NET

Upvotes: 5

Related Questions