开发者

Changing an "." to an "_" in a C# string

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 j开发者_运维问答ust seems to ignore it. Any ideas?

Best Regards


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.


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.


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.


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('.', '_');


String input = "1.1.1";
input = input.Replace(".", "_");


strings are immutable, so make sure you're using it like this:

string myString = "1.1.1";
myString = myString.Replace('.', '_');


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜