String and StringBuilder Classes

Strings are plays a major role in our programming world. To deal with these Strings we are using String and StringBuilder classes.

String

A string is a sequential collection of Unicode characters that is used to represent text. String is a class which belongs to the namespace System. String.

String Concatenation can be done using '+' opearator or String.Concat method.

String.Concat method concatenates one or more instances of String.

Sample code:

  1. string string1 = "Today is " + DateTime.Now.ToString ("D") + ".";  
  2. Console.WriteLine (string1);  
  3.   
  4. string string2 = "Hi " + "This is Jitendra ";  
  5. string2 += "SampathiRao.";  
  6. Console.WriteLine(string2);  
StringBuilder

StringBuilder is a class which belongs to the namespace System.Text. This class cannot be inherited.

In StringBuilder we are using Append() method.

Sample code:

  1. StringBuilder number = new StringBuilder (10000);  
  2. for (int i = 0; i<1000; i++)  
  3. {  
  4.     return Number.Append (i.ToString ());  
  5. }  
So where we can use these classes?

The answer is for simple String manipulations we can use String class. But the string manipulations are more it is better to use StringBuilder class.

Why the StringBuilder class is better for more string manipulations instead of String class?

The String object is immutable. Every time you use one of the methods in the System. String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. It's nothing but performance of the application might be decreased. So we are using StringBuilder in such cases.

StringBuilder object is mutable. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop."

Differences between String and StringBuilder:

It belongs to String namespace It belongs to String. Text namespace
String object is immutable StringBuilder object is mutable
Assigning: String s= "something important"; Assigning:
We can use '+' operator or Concat method to concatenate the strings. Here we are using Append method.
When string concatenation happens, additional memory will be allocated. Here additional memory will be allocated when the string buffer capacity exceeds only.


Similar Articles