Him_Jalpert
Him_Jalpert

Reputation: 2516

String.Replace using multiple values

I was looking at some code from a co-worker and it looks as though they're using a Char Array in their String.Replace:

txtPAPTransit.Text = g_aAllBranches(instApplication.branchForCumisReporting.ToLower).transit.ToString.Replace({" "c, "-"c}, "").Substring(3)

Which doesn't remove the "-" from the string in the textbox (the string being 123-45678). When I try it making the Substring as 4 instead of 3, it works. Which strikes me as very odd, why would it behave like this in this case when the index is 0 based?

When I write the replace like this it works fine:

txtPAPTransit.Text = g_aAllBranches(instApplication.branchForCumisReporting.ToLower).transit.ToString.Replace("-"c, "").Substring(3)

Afterwards the string appears as 45678, which is the correct result.

Why would it work in the case of replacing the substring with 4 as I mention above? And why does it have a problem with the char array?

Upvotes: 2

Views: 83

Answers (1)

The Replace usage is not correct - or your co-workers understanding of it is flawed. The 2 overloads are:

- String.Replace(Char, Char)  
- String.Replace(String, String)

So, Replace({" "c, "-"c}, "") will not act to replace any space and any dash with String.Empty. Instead, since a char array is a string, it will look to replace " -" (space+dash) as in "123 -45678".

The correct way to replace either would be:

Dim sample = "123- ABCDEFG"     
newTxt = sample.Replace(" "c, "").Replace("-"c, "")

"123ABCDEFG"

Upvotes: 3

Related Questions