16 - Strings in C#

16.1 Creating string in C#

A string is an object of type String that stores the value in the form of a text. The text is stored as a sequence of read only characters stored in an array. The string in C# contains embedded null characters (‘\O’). The string keyword in C# is an alias for String. The String class provides various string operations as creating, manipulating, concatenating and comparing the values.

String objects can be created by any of the following methods as mentioned below:

a) Assigning a string literal to a String variable

string name;
name = “Jennifer”;

Console.WriteLine( “The name is:”+name );

The string literal is assigned to the name variable of type string.

b) Using the string concatenation

string name, level;
name = “Jennifer”;

level = “MBA”;

string value = name + level;
Console.WriteLine( “The detail is:”+name +level );

The value variable contains the concatenation of two strings as name and level respectively.

c) Using the String class constructor

static void Main) string[ ] args )
    char[ ] location = new char [7] { ‘N’, ‘e’, ‘w’, ‘Y’, ‘o’, ’r’ ,’k’};
     string address1 = new string(location);

The location array contains the elements of char type. The variable of type string is used to display values.

d) Retrieving property or calling a method that returns a string

string[ ] data = new string[] {“Learn”, “Strings”, “In”, “C#”};
string output = String.Join (“ “, data);


The Join method is used for combining the values in the string array.

e) The method used for formatting or converting the value to specific string representation

DateTime d = new DataTime (2014, 10, 1, 10, 30, 15);
string values = String.Format(“Message sent on {0:t} on {0:D}”, d);
Console.WriteLibe(“The value is:{0}”, values);


The Date and Time when the user communicated is displayed using the DateTime method of C#.

16.2 Properties of string class

The String type has two properties as mentioned below:




It gets the Char object at a specified position in the current String object


It gets the number of characters in the current String object

A code sample to demonstrate the properties in C# is as shown below:

class Program
    static void Main( string[ ] args )
        string str1 = “Welcome”;
        for ( int c=0; c<str1.Length-1; c++);
        Console.WriteLine(“{0}”, str1[c]);
        Console.WriteLine(“The length of the string ‘{0}’ is {1}”, str1, str1.Length);

The output for the code is as shown below:

16.3 Methods of string class

Some of the methods of the string class are as shown below:




It is used to make the clone of the string


It compares the two specified strings and returns the integer value


It is used for concatenation of two string objects


It is checks whether the specified character or string exists in the string value


It creates a new string object with the same value as the specified string


It is used to check whether the specified character is the last character of the string


It compares two strings and returns the Boolean value as output


It returns the HashValue of the specified string


It returns the System.Type of the current instance


It returns the index position of the first occurrence of the specified character


It converts the string into lower case


It converts the string into upper case


It inserts the string or character in the string at a specific position


It returns the index position of last occurrence of the specified character


It is used to delete all the characters from the beginning to the specific position


It is used to replace a character in the string


It splits the string based on the specific value


It checks the first character of the string matches with the specific character


It is used to return the substring


It converts the string to the character array


It removes the extra whitespaces from the beginning and the end of the string


class Program
    static void Main ( string[ ] args )
        string city;
        city = “London”;
        string country;
        country = “United Kingdom”;

        //The clone of the string is created

        //It compares the two strings and returns 0 if True else 1 for false  
        //It checks whether the specified character is the last character

        //It checks whether the value specified is present in the string

        //It compares the two strings and returns to true or false

        //It is used for the comparison of two strings

        //It is used for returning the Hash code for the string

        //It converts the string to Lower case

        //It converts the string to upper case  
        Console.WriteLine(country.Insert ( 0, “A”));
        //Inserts the value at the specified position

        //Returns the last index value of the specified value

        //Removes the character from the specified position

        //Returns the first character of the string with the specified value

        //Returns the substring of the specified string

        //removes the starting and ending whitespaces in the string

        string[ ] split = city.Split(new char[] {“0”});        

Sample code for demonstrating the methods of string class in C# is as shown below:

The output for the code is as shown below:

16.4 Example of string in C#

class Program
    static void Main ( string[ ] args )
        string s1 = “Strings are literals”;
        string s2 = “Values are assigned to the variables”;
        s1 = s1 + s2;

        string s3 = “Reverse letters”;
        for ( int i=0; i<14; i++)
            Console.WriteLine(s3[ s3.Length – i – 1] );
        string [ ] data = { “C# data”, “Array data”, “collection of data”};
        string pattern = “data”;
        foreach ( string s in data )
            Console.Write(“{0,9}”, s);
            if ( System.Text.RegularExpression.Regex.IsMatch ( s, pattern , System.Text.RegularExpressions.RegexOptions.IgnoreCase) );
                Console.WriteLine((“match for {0} found), pattern );

A sample code to demonstrate the string functionality in C# is as shown below:

The output for the code is as shown below:

In the above code, the concatenation, reverse of string and identifying values through regular expressions is performed on different string variables. The output received after applying various functions is as shown above.

Like us on Facebook