String and String Builder classes
DownLoad link: Click Here
Strings are plays a major role in our programming world. To deal with these Strings we are using String and StringBuilder classes.
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.
string string1 = “Today is ” + DateTime.Now.ToString (“D”) + “.”;
string string2 = “Hi ” + “This is Jitendra “;
string2 += “SampathiRao.”;
StringBuilder: StringBuilder is a class which belongs to the namespace System.Text. This class cannot be inherited.
In StringBuilder we are using Append () method.
StringBuilder number = new StringBuilder (10000);
for (int i = 0; i<1000; i++)
returnNumber.Append (i.ToString ());
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|
String s= ”something important”;
StringBuilder sbuild= new StringBuilder(“something important”);
|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.|