Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it required to check before replacing a string in StringBuilder (using functions like "Contains" or "IndexOf")?

Is there any method IndexOf or Contains in C#. Below is the code:

var sb = new StringBuilder(mystring);
sb.Replace("abc", "a");
string dateFormatString = sb.ToString();

if (sb.ToString().Contains("def"))
{
    sb.Replace("def", "aa");
}


if (sb.ToString().Contains("ghi"))
{
    sb.Replace("ghi", "assd");
}

As you might have noticed I am using ToString() above again and again which I want to avoid as it is creating new string everytime. Can you help me how can I avoid it?

like image 475
Rocky Singh Avatar asked Jun 21 '11 10:06

Rocky Singh


1 Answers

If the StringBuilder doesn't contain "def" then performing the replacement won't cause any problems, so just use:

var sb = new StringBuilder(mystring);
sb.Replace("abc", "a");
sb.Replace("def", "aa");
sb.Replace("ghi", "assd");
like image 170
Jon Skeet Avatar answered Oct 18 '22 14:10

Jon Skeet