Replacing all the occurences of a string with new value

In a string text, if some texts which occur at many places, need to be replaced by some different value then a regular expression can be used.This can be done by using System.Text.RegularExpressions.Regex class of .NET framework.

For example suppose a string variable str contains "This is <> and it used by the regex class.The value for <> will be replaced." We want to replace all the occurences of placeholder <> with some name say "DOTNETSPIDER" then the following code will do this -

using System.Text.RegularExpressions;

class ReplaceDemo
public string ReplaceName(string originalText,string name)
originalText =Regex.Replace(originalText, <>, name);

The above "ReplaceName()" function will return the following value if passed the string str and "DOTNETSPIDER" in the function -
"This is DOTNETSPIDER and it used by the regex class.The value for DOTNETSPIDER will be replaced."
It is clear that all the occurences of <> is replaced with "DOTNETSPIDER" in a single c# statement.



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: