String.Replace works in VB but not C #

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

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

However, the same C # code does not:

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

This will not compile as it says

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

How does it work in VB but not in C #? and how can i fix it?

I thought this might be like C # string.Replace not working , but this implies that this code will infilate.

Similarly with another line. Replace the questions: string.Replace (or some other modification of the string) doesn't work , it looks like they will compress the compilation, while mine won't.

+4
source share
6 answers

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

If you just want to delete everything, use this:

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

Based on your code, you might want to replace the last instance, so try this if you want:

 StringBuilder sb = new StringBuilder(strLine); sb[strLine.LastIndexOf(",")] = ""; strLine = sb.ToString(); 
+8
source

Reading the documentation , I am amazed that the first example works in general. string.Replace should receive either a pair of characters or a pair of strings, not an integer, and then a string. Pheraps version of VB automatically converts an integer to its char representation?

+1
source

Try to execute

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

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

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

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

In C #, this will do what you want:

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

Hope this helps.

0
source

you can use String.Remove

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

All Articles