Reputation: 33
I'm developing a piece of software in C# and the end result is an Excel spreadsheet. The title of the spreadsheet is created using several variables to explain exactly what the spreadsheet is. One of the variables is a string which contains data like this:
'1.1.1'
I need to convert it at the point of creating the spreadsheet to be:
'1_1_1'
I have tried using the String.Replace
method but it just seems to ignore it. Any ideas?
Best Regards
Upvotes: 3
Views: 881
Reputation:
String.Replace
is the right way to do this:
private void button1_Click(object sender, RoutedEventArgs e) {
String myNumbers = "1.1.1";
Console.WriteLine("after replace: " + myNumbers);
myNumbers = myNumbers.Replace(".", "_");
Console.WriteLine("after replace: " + myNumbers);
}
will produce:
after replace: 1.1.1
after replace: 1_1_1
Upvotes: 0
Reputation: 15237
strings are immutable, so make sure you're using it like this:
string myString = "1.1.1";
myString = myString.Replace('.', '_');
Upvotes: 0
Reputation: 359966
If I had to guess, you're not capturing the value returned by String.Replace
. Strings are immutable, so String.Replace
returns a new string, which you need to store a reference to.
string foo = "1.1.1";
foo = foo.Replace('.', '_');
Upvotes: 2
Reputation: 70022
When you use string.Replace
are you remembering that you have to assign it?
yourString.Replace(".", "_");
Will do nothing.
string newString = yourString.Replace(".", "_");
will return the string with the dots replaced with underscores.
Upvotes: 4
Reputation: 17808
I bet you doing this:
myString.Replace(".","_");
When you should be doing this:
myString = myString.Replace(".","_");
Remember, in .Net strings are immutable, so any changes result in a new string.
Upvotes: 35
Reputation: 1502985
Chances are you're ignoring the result of string.Replace
. You need:
text = text.Replace('.', '_');
Just calling Replace
doesn't change the existing string - it creates a new string and returns it. Strings are immutable in .NET - they never change after creation.
Upvotes: 12