Manipulating strings

Strings are a very important data type in C#. The string data type is used for saving text as string. In programming terms, it's a sequence of characters. String is a reference type variable unlike other basic data type variables, such as int, float, and double, which are value type variables. Also, strings are immutable in nature, that is, the values present in them cannot change. In this section, we will look at different operations related to this data type.

So, look at the following code example:

string s = "Hello";
s = "world";

When we are assigning a Test value to the already declared string objects, internally, CLR allocates a new memory block for the modified string object. Hence, for every operation that we do on a string, instead of modifying of the same string object, a new string object is declared in CLR. Due to this, we need to be very careful while doing operations on string, for example, if we execute the following loop operation on a string object:

string s = String.Empty;
for(int z = 0; z < 100; z++)
{
s = + "a";
}

In the preceding code, we are concatenating the string object, s, with a character, a, in the loop. This loop will run 100 times. Therefore, the CLR will go on allocating more and more memory for the string object. Hence, due to memory usage, performance-wise, the preceding operation is not good. 

To help to improve this feature in string, C# provides us with two built-in classes, Stringbuilder and StringWriter, which we will discuss next. We will also look at some of the features available with us for executing string searching in C#.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.171.193