The string is the most important data type ni C#. String with reference type and the word string is an alias for the class ‘System.String’. There is no difference between keywords ‘String’ and ‘string’, both creates the object of ‘System.String’ class.

The string represents the series of zero or more Unicode characters. The string is the reference type, but it is treated like value types that mean we declare variables, initialize variables and do some operations on the string just like other value types.

Declaration and Initialization of string variables:

The most common way to create the string is using string literal as below:

string str;//Declaration 
str=”C# programming”;//Initialization

One can merge declaration and initialization one statement as below: 

string str==”C# programming”;

The other way is to constructing the string from character array as below:

char[] chars={‘A’, ‘B’, ‘C’, ‘D’}; 
string str=new string(chars); 
There is a way to create string with empty constant as below 
string str=System.String.Empty;

Using empty constant eliminate the chances of “NullPointerException”.

Following program shows declaration and initialization of string:

 

using System; 
namespace StringInitialization 
{ 
    class Program 
    {
        static void Main(string[] args) 
        {
            string str1 = "I am happy."; 
            char[] chars = { 'A', 'B', 'C', 'D' }; 
            string str2 = new string(chars);
            Console.WriteLine(str1); 
            Console.WriteLine(str2); 
            Console.ReadLine(); 
        } 
    } 
}

The output of above program is: 

I am happy. 
ABCD

Regular and Verbatim string Literals:

The value of string variables are assigned two ways; in a regular way (double quoted) and verbatim string (@quoted) as below:

string str=”This is C# programming”;

OR

string str=@”This is C# programming”;

The difference between these two is that regular string process the escape character sequence (like \n, \t etc.) but the verbatim string does not process escape sequence instead it print that sequence as it is.

If you want the escape sequence to be a part of string value in the regular string then use a backslash. The following program demonstrates the difference between regular string and verbatim string.

using System; 
namespace StringDemo 
{ 
    class Program 
    {
         static void Main(string[] args)
         { 
              // Regular string 
              string S1 = "C# is \n programming language.";         
             // Regular string with escape sequence as part of string 
              string S2 = "C# is \\n programming language.";     
              // Verbatim string 
               string S3 = @"C# is \n programming language.";                
               Console.WriteLine(S1);
               Console.WriteLine(S2); 
               Console.WriteLine(S3);
               Console.ReadLine(); 
          } 
     } 
}

The output of above program is: 

C# is 
programming language. 
C# is \n programming language. 
C# is \n programming language.

 Accessing individual characters and length of the string

The length property of string class returns the length of the string. Strings are indexed based. We can access the individual characters in a string by its index like an array. The index starts with zero and the index of the last character is length-1.

string str=”Happy Coding”; 
int len=str.Length;//This will return length of string and stored it in len 
char c=str[0];//This returns the first character of string and assigned it to variable c

Concatenating strings:

One can join two or multiple strings or two string literals using operator ‘+’. The plus operator combines all the string and returns the new object of combined string. The other way to join strings is Concat() method of String class. This method takes string objects or string literal as the parameter and return concatenated string.

The other way to join strings is Concat() method of String class. This method takes string objects or string literal as the parameter and return concatenated string.

using System; 
namespace StringConcat 
{ 
   class Program 
   {
       static void Main(string[] args) 
       { 
           string s1 = "World is "; 
           string s2 = "very beautiful place"; 
           string s3 = s1 + s2; 
           string s4 = string.Concat(s1 , s2," to live"); 
           Console.WriteLine(s3); 
           Console.WriteLine(s4); 
           Console.ReadLine(); 
       }
   }
}

The output of above program is: 

World is very beautiful place 
World is very beautiful place to live

Substrings:

Many times there is a requirement of getting some part string. In this situation Substring () method of string class is very useful. This method has two forms as below

string Substring(int startindex); 
string Substring(int startindex, int count);

If you provide only start index for the Substring() method then it returns substring starting from given start index to the end of the string. In second form count is the number of characters to return in substring starting from start index.

using System; 
namespace SubStringDemo 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            string str = "Happy coding";
            string s1 = str.Substring(6); 
            string s2 = str.Substring(0, 5); 
            Console.WriteLine(s1); 
            Console.WriteLine(s2);
            Console.ReadLine(); 
        } 
    } 
}

The output of above program is: 

coding 
Happy

 

Recommended Post   C# OOPS

Some of the other useful methods of String class are as follows; 

 

 

Method Description
Contains() It checks if given argument string is present or not in the string.
EndsWith() It checks if the string ends with specified string or not.
StartWith() It checks if the string starts with specified string or not.
ToLower() It returns the string in lower case.
ToUpper() It returns the string in upper case.
Trim() It returns a string with removed leading and trailing white spaces from a string.
TrimEnd() It returns the string with removed trailing white spaces.
TrimStart() It returns the string with removed leading white spaces.
SubString() It returns some part of string
Split() It split the string into parts based on conditions and return an array of strings.
ToCharArray() It returns array of characters  in string
Replace() Itreplacessingle character or some part of the string with the new value.
IndexOf() It returns the index of the first occurrence of character or string.
LastIndexOf() It returns the index of the last occurrence of character or string.

 

 

Below program gives the idea of how to use string methods:

using System; 
namespace StringOperations 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            string str = "Ram is very good person."; 
            Console.WriteLine(str.ToUpper()); 
            Console.WriteLine(str.ToLower());
            if (str.Contains("good")) 
            { 
               Console.WriteLine("The string contains the word good."); 
            } 
            else 
            { 
               Console.WriteLine("The string not contains the word good."); 
            } 
            if (str.StartsWith("A")
            {
               Console.WriteLine("The string is start with A."); 
            } 
            else 
            { 
               Console.WriteLine("The string is not start with A"); 
            } 
            Console.WriteLine("The index of e is {0}",str.IndexOf('e')); 
            Console.WriteLine("The last index of o is {0}", str.IndexOf("o")); 
            string str1 = "     C# is object oriented language.     "; 
            Console.WriteLine(str1.Trim()); 
            Console.WriteLine(str1.TrimStart()); 
            Console.WriteLine(str1.TrimEnd());
            Console.ReadLine(); 
        } 
   } 
}

 

Recommended Post   C# Classes & Objects 

The output of above program is: 

RAM IS VERY GOOD PERSON. 
ram is very good person. 
The string contains the word good. 
The string is not start with A 
The index of e is 8 
The last index of o is 13 
C# is object oriented language. 
C# is object oriented language. 
C# is object oriented language.

Immutable strings:  

String in C# is immutable that means when we make any changes in the existing string it does not change the current object, instead, it create the new object in and stored that reference invariable.

using System;
 namespace ImmutableString
 {
   class Program
  {
     static void Main(string[] args)
     {
        string str1 = "C# is very  ";
        string str2 = str1;
        str1 += "good programming language.";
        Console.WriteLine(str1);
        Console.WriteLine(str2);
        Console.ReadLine();
     }
   }
}

The output of above program is:

C# is very good programming language.
C# is very

In above program, first string str1 is created and then str1 is assigned to string str2. Now both reference variables refer to the same string object, but when we try to change the contents of the string, the new string object is created and string with changes are stored in it then variable str1 start to refer this new object. But variable str2 still refers to the old object.

StringBuilder Class: 

As we learn string is immutable and every time when changes are made in the string content new object created. So it affects the performance if we are working with large strings and content of string going to change many times.

In this scenario, we can use ‘StringBuilder’ class for creating strings. StringBuilder is mutable and we can make the change in the existing object.

This class is present in ‘System.Text’ namespace. The following program demonstrates how to use StringBuilder class.

using System;
using System.Text;
namespace StringBuilderDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder strDemo = new StringBuilder();
            strDemo.Append("C# is ");
            strDemo.Append("good programming language.");
            Console.WriteLine(strDemo.ToString());
            Console.ReadLine();
         }
     }
}

 

Recommended Post   Access Modifiers in C#

The output of above program is:

C# is good programming language.

 

 

SHARE
Previous articleC# Boxing and Unboxing
Next articleC# OOPS

LEAVE A REPLY

Please enter your comment!
Please enter your name here