Home > Tutorial for Beginners > Tutorial on Strings in C#

Tutorial on Strings in C#

Strings always perform very important role in all languages. They used to manipulate a string.  In .Net strings are the Class objects. They are reference type in .Net and are store in Heap instead of stack. Because they are reference types they So they impact the performance and sometime they become very costly. However .Net has other options too, to handle this situation like ArrayList. We can create dynamic Array using ArrayList which is faster than normal string operations. It’s advisable to use less string as much as possible. .Net strings are immutable means it always creates a new object of string even you modify the existing string object, so again it’s a performance hit.

In all OOP strings functions are implemented either as a property or method of string objects. Here is the list of few important string functions in .Net(C#)

Substring: will return the specified string, it has two overloaded function in .Net
·         Substring(startIndex):  This method accept only one integer parameter, In this method you can return the string from the start index value pass to your method, In below code as I am passing 4 so the out put will be “t String“.
    string str1 = “Test String”;
       string strResult = str1.Substring(3);
       Response.Write(strResult + “</br>”);

·         Substring (startIndex, length):  When you want to extract a part of string then you can use this method. In my below code I wanted to extract “string” part from “Test String” string. See below how I can achieve
    string str1 = “Test String”;
       string strResult = str1.Substring(0,4);
       Response.Write(strResult + “</br>”);
Length:  It is used to return the total number of character in specified string.
    string str1 = “Test String”;
       Response.Write(strResult.Length + “</br>”);

IndexOf: It is used to return the first index of  specified objects or character object It has 9 flavors in .Net (Asp.net 4.0). In case the specified string is not found then it will return the -1.
string str1 = “Test String”;
        Response.Write(strResult.IndexOf(“g”) + “</br>”);

Split: By using split function you can break your string into an array on the basis of specifying delimiters.  In my below code I am breaking my string on the basis of space between my string ” “, so the length of my array will be two.

       string str1 = “Test String”;
       char[]delimiters = new char[] { ‘ ‘ };
       string [] strFinal = str1.Split(delimiters);
       foreach (string arrStr in strFinal)
           Response.Write(arrStr + “</br>”);


Read Part 2: String Manipulation Functions in C#

A Must Read: Difference – string and String. How to decide which one should be used?

Post Comments Below