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.
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();
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?
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(',', '');
Try the following
string.Replace("," , "");
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.
you can use String.Remove
strLine = strLine.Remove(strLine.LastIndexOf(','), 1);
Related
I have an issue with taking a number string from SQL and putting it into excel, but excel formats the number without it's leading zeros.
Another program I wrote reads the excel and put it into a pdf. It is in this second program I decided to reappend the missing leading zeros.
I am using .PadLeft to do this and ran into some errors. For documentation sake, I am going to add this issue I found to SO and also answer it.
Here was my problem:
I need the number string to be 10 digits, with zeros on the front up to 10 digits.
I have numbers like 77776666 coming from excel, they should be 0077776666 (10 digits)
Here is what DIDN'T work. It did not append any zeros:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "");
insuranceID.PadLeft(10, '0');
To make this code work, I actually had to write the code like so:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "");
insuranceID = insuranceID.PadLeft(10, '0');
It had to have the assignment part of the code on the front of the .PadLeft bit.
I didn't find an answer to this on SO and just discovered my answer. I hope this helps someone.
In C# Strings/strings are immutable, so simply declaring string.PadLeft(x, '0') will not work.
Try this instead:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "");
insuranceID = insuranceID.PadLeft(10, '0');
To save you time in the future, the immutability of strings also comes into play for many of the string methods such as string.Replace(), string.ToUpper(), string.ToLower(), etc.
You could have also just used your original code but append the .PadLeft(10, '0') to the end of your statement and remove your second line, like this:
string insuranceID = Convert.ToString(xlRange.Cells[i, 21].Value2 ?? "").PadLeft(10, '0');
Thus eliminating the need to create a separate statement other than possibly for debugging purposes.
What am I missing:
decVal = Decimal.Parse(myAr[0]);
Or
Decimal.TryParse(myAr[0], out decVal);
Fails !
Input string was not in correct foramt.
myAr[0] is "678016".
Tried to add NumberStyle.Any and CultureInfo.InvarialtCulture but got the same results.
More info on the string:
it is concatenated with some letters in hebrew and a "\u200e" space between them. and then I use split(' ') to get the numbers back.
This is probably the source of this error, but when I check the myAr[0] in the watch it is pure string....
Guys I've found the answer, I'll rewrite the question for future generation.
The Original string was a concatenation of letters and numbers separated with a special sequence to preserve the order in a rtl situation: "\u200E".
The number where extracted later using string.split(' ') which seems to work OK (in the watch) be it caused the problem.
once I used string.split("\u200e").ToCharArray() I got the same results, but now the decimal.Parse is working.
It looks like the special char was still inside the string, invisible to the watch.
This is weird, on my machine (.NET 4) even this works:
Decimal.TryParse("asdf123&*", out someDecimal);
By works I mean that TryParse returns false, no exception is thrown.
Parse method may throw an exception - maybe you have some whitespace or string literally contains " (quotes)?
I am having a few problems with trying to replace backslashes in a date string on C# .net.
So far I am using:
string.Replace(#"\","-")
but it hasnt done the replacement. Could anyone please help?
string.Replace does not modify the string itself but returns a new string, which most likely you are throwing away. Do this instead:
myString= myString.Replace(#"\","-");
On a side note, this kind of operation is usually seen in code that manually mucks around with formatted date strings. Most of the time there is a better way to do what you want (which is?) than things like this.
as all of them saying you need to take value back in the variable.
so it should be
val1= val1.Replace(#"\","-");
Or
val1= val1.Replace("\\","-");
but not only .. below one will not work
val1.Replace(#"\","-");
Use it this way.
oldstring = oldstring.Replace(#"\","-");
Look for String.Replace return type.
Its a function which returns a corrected string. If it would have simply changed old string then it would had a void return type.
You could also use:
myString = myString.Replace('\\', '-'));
but just letting you know, date slashes are usually forward ones /, and not backslashes \.
As suggested by others that String.Replace doesn't update the original string object but it returns a new string instead.
myString= myString.Replace(#"\","-");
It's worthwhile for you to understand that string is immutable in C# basically to make it thread-safe. More details about strings and why they are immutable please see links here and here
I'm trying to replace ' with its HTML entity reference using the String.Replace function. So a'a becomes a’a which is correct, but if I try to make the inverse (from the string above back to a'a) the output is always a’a.
I've noticed that if I try to replace only the code #8217; without the & character everything works fine, so maybe that the & character is a part of the problem.
This code works fine:
string s0 = "a'a";
string s1 = s0.Replace("'", "’");
string s2 = s1.Replace("’", "'");
Could you give us more information?
I don't know whats your problem, this little code works just perfect:
String test = "a’a";
Console.WriteLine(test.Replace("’", "'"));
I think its is string delimiters i.e ",' are interrupting normal string delimiters.
I would like to do the following:
if (string.Contains("/"))
{
string.Replace("/", "\/"); //this isn't valid
}
I've tried
string.Replace("/", "\\/");
but this gives me what I started with. How can I do this?
Thanks
Strings are immutable, which means that any modification you do to a string results in a new one, you should assign the result of the Replace method:
if (myString.Contains("/"))
{
myString = myString.Replace("/", "\\/");
}
String.Replace returns the string with replacements made - it doesn't change the string itself. It can't; strings are immutable. You need something like:
text = text.Replace("/", "\\/");
(In future examples, it would be helpful if you could use valid variable names btw. It means that those wishing to respond with working code can use the same names as you've used.)
One way is to use a verbatim string literal
string.Replace("/", #"\");