Simple Usage of stringBuilder class

Bubbly
Posted by Bubbly under C# category on | Views : 2055
This code shows sample usage of StringBuilder class

private void btnstringBuilder_Click(object sender, System.EventArgs e)
{
// Demonstrate the stringBuilder class.
// stringBuilder is provided by the System.Text
// namespace.

StringBuilder sbdata = new StringBuilder("The place is much more interesting than I thought");
sbdata.Insert(19, " cool");
sbdata.Remove(10, 6);
sbdata.Replace("much", "quite");
sbdata.AppendFormat(" {0} times in {1} minutes", 17, 2);

int intPos;
intPos = sbdata.ToString().IndexOf("place");
if (intPos > 0)
{
sbdata.Insert(intPos + "place".Length, ", ");
}

// stringBuilder is significantly more efficient for
// this sort of operation.
string str = "The place is much more interesting than I thought";

str = str.Insert(19, " cool");
str = str.Remove(10, 6);
str = str.Replace("much", "quite");
str += string.Format("{0} times in {1} minutes", 17, 2);
intPos = str.IndexOf("place");
if (intPos > 0)
{
str = str.Insert(intPos + "place".Length, ", ");
}
txtResults.AppendText("SB output: " + sbdata.ToString() + Environment.NewLine);
txtResults.AppendText("S output: " + str + Environment.NewLine);
}

Comments or Responses

Login to post response