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

Viewed 21899

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?

4 Answers
Related