Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Replace working in VB but not C#

Tags:

string

c#

replace

The following VB code works correctly and does not flag up any errors.

strLine = strLine.Replace(strLine.LastIndexOf(","), "")

However the same C# code doesn't:

strLine = strLine.Replace(strLine.LastIndexOf(","), "");

This will not compile as it says

The best overloaded method for 'string.Replace(string,string)' has some invalid arguements.

How come this works in VB but not in C#? and how do I fix this?

I thought it might be similar to C# string.Replace doesn't work but it implies that that code will infact complile.

Likewise with other string.Replace questions: string.Replace (or other string modification) not working, it appears they will infact compile, whereas mine will not.

like image 938
Ewan Avatar asked Jan 14 '23 11:01

Ewan


2 Answers

LastIndexOf returns an integer, not a string. Replace takes string, string as parameters, you're passing it int, string, hence the exception The best overloaded method for 'string.Replace(string,string)' has some invalid arguements.

If you're just looking to remove all , use this:

strLine = strLine.Replace(",", "");

Based on your code, you may be only wanting to replace the last instance of , so try this if that's what you want:

StringBuilder sb = new StringBuilder(strLine);
sb[strLine.LastIndexOf(",")] = "";
strLine = sb.ToString();
like image 189
tnw Avatar answered Jan 22 '23 12:01

tnw


Reading the documentation, I'm amazed that the first example works at all. string.Replace should receive either a couple of chars or a couple of strings, not an integer and then a string. Pheraps the VB version is converting the integer to its char representation automatically?

like image 36
Geeky Guy Avatar answered Jan 22 '23 14:01

Geeky Guy