Ewan
Ewan

Reputation: 357

String.Replace working in VB but not C#

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.

Upvotes: 4

Views: 383

Answers (6)

Damith
Damith

Reputation: 63105

you can use String.Remove

strLine = strLine.Remove(strLine.LastIndexOf(','), 1);

Upvotes: 0

Rodrigo Taboada
Rodrigo Taboada

Reputation: 2727

In C# LastIndexOf returns an int, but Replace expects a string or a char as the first argument. I don't know VB to explain why your code works, but I can explain that in C# you can't pass an integer where a string or a char is expected.

In C#, this will do what you want:

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

Hope that helps.

Upvotes: 0

DotNetRussell
DotNetRussell

Reputation: 9863

Try the following

string.Replace("," , "");

Upvotes: 0

tnw
tnw

Reputation: 13887

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();

Upvotes: 8

diwatu
diwatu

Reputation: 5699

In c# the String.Replace's first parameter must be either char or string, but you are using a integer(string.LastIndexOf returns a integer). Why not just use:

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

Upvotes: 0

Geeky Guy
Geeky Guy

Reputation: 9379

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?

Upvotes: 1

Related Questions