Thursday, December 16, 2010

Replacing character in string in C#

The "string" library in C# provides many features which makes string manipulation a piece of cake. Of these many functions, one is the function "Replace".

As the name suggests 'Replace', replaces all occurrences of one character, or a string with another provided character of string. (Eg. below would clear the concept)

The function has one overload.

Replace(char oldvalue, char newvalue)
Replace(string oldvalue, string newvalue)

The first one is used to replace occurrence of a particular character, for example, you want to replace all occurrences of 1 with 2.

The second one is used to replace occurrence of a particular string (oldvalue) with a provided string (newvalue).

Example:


string str = "this is a sample string.";
Console.WriteLine(str);
string strReplaced = str.Replace('.', ',');
Console.WriteLine(strReplaced);
strReplaced = str.Replace("this", "given");
Console.WriteLine(strReplaced);


Output:

this is a sample string.
this is a sample string,
given is a sample string.



Example 1


Please note that the comma replaced in the second step is not there anymore in the third step. This is because the replace function did not replace AND store the full stop with comma in the string str, rather it replaced the full stop with the comma and stored it in strReplaced only.

The point to note is that the replace is not done in place, rather the string remains unchanged and a new string is returned by the function with the replaced value.

So if you want the same string to have the replaced values, what you can do is assign the string output returned by the 'Replace' function with the same string.

That is,

string str = "this is a sample string.";
Console.WriteLine(str);
str = str.Replace('.', ',');
Console.WriteLine(str);
str = str.Replace("this", "given");
Console.WriteLine(str);


Output:
this is a sample string.
this is a sample string,
given is a sample string,



Example 2

No comments:

Post a Comment