Wednesday, February 22, 2017

best practice to replace in C#

In most of the application we have to replace a string with some value and sometimes it has to be used multiple times for multiple characters. Like first replace the dot(.) and then hyphen(-) and then some other characters. by using String.Replace(String,String) method we can easily replace one characters or we can use regular expression to replace the characters or stings.


So for one character replacement there we can use only one String.Replace(String, String) by passing the new and old characters. But when we have to replace multiple characters then what is the best way to do? Lets see.


We can do this in two ways.


1. Using multiple Replace() method:


string demo = "This, is. my-text/ Remove, all= unwanted characters.";
 
// not a good practice
demo = demo.Replace(",", "");
demo = demo.Replace("/", "");
demo = demo.Replace("=", "");


This way you can replace the characters but there is a better way to do this.


// best practice
demo = demo.Replace(",", "").
            Replace("/", "").
            Replace("=", "");


Now this piece of code will save both time and space complexity to replace the desired characters.


2. Using Regular expression:


For multiple characters we can use regular expression to matching the string content and then replace the characters with the new values.


Let us took the previous example where we have to replace ",", "/" & "=" with blank value. So, our regular expression will be something like this. 


[,/=]
And the code will be like
Regex rgx = new Regex(@"[,/=]");
demo = rgx.Replace(demo, ""); 
Note:
[a-z]
Matches any lowercase ASCII letter.
We only need to match words with lowercase first letters.
This is a character range expression.
\b
 
Word break:
Matches where a word starts.
\w+
 
Word characters:
Matches must have one or more characters.
\n
Replace new line with new value.


2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

Popular Posts

Pageviews