Signup/Sign In

C# Strings

Posted in Programming   LAST UPDATED: OCTOBER 14, 2019

    In this article, we will learn about strings in C# programming where we will cover: what is a string, what are the different types of string, what is the difference between string and String in C#, why string is immutable in C#, and so on. Furthermore, we will see the implementation of various string properties and methods. We will perform operations on strings like comparing and concatenating two strings, finding the substring, transforming, etc. So, let's get started.


    What is a string and what is the difference between string and System.String?

    A string is a sequence/array of characters and it is a type of object(reference type) in C# programming. The value of a string is a text(stored as a sequential read-only collection of Char objects). There is no difference between string and System.String, they are equivalent(the string keyword is an alias for String). Also, the string class inherits the properties and methods of the System.String class hence, we can prefer either of the naming conventions.


    Why string is immutable in C#?

    In the object-oriented programming languages, immutable means an object whose state can't be modified once created. In the same way, in C# string objects are immutable, and they can’t be changed once it has been created. As we know, the string value is text and internally, it is stored as a sequential read-only collection of char objects, hence whenever we change the value stored in a string object a new object is created rather than the existing one getting modified. Hence, in C# string is immutable.


    Declaring and Initializing Strings

    When we are creating a string literal, we are actually creating a string object. Let's take an example which shows the ways to declare and initialize strings.

    Filename: Program.cs

    using System;
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string s1;
                string s2 = null;
                string s3 = ""; // string s3 = String.Empty;
                string s4 = "Studytonight";
                Console.WriteLine(s4);
                var v1 = "This is a string";
                Console.WriteLine(v1);
                const string s5 = "We can't change the value of a constant string";
                Console.WriteLine(s5);
                char[] c1 = { '1', '2', '3' };
                string s6 = new string(c1);
                Console.WriteLine(s6);
                
                string path = @"d:\drivers\mongodriver\...";
                Console.WriteLine(path);
            }
        }
    }

    Output:

    Studytonight
    This is a string
    We can't change the value of a constant string
    123
    d:\drivers\mongodriver\...

    In the above program, s1 is just the declaration, s2 is the null, and s3 is an empty string. The difference between null and empty string is that an empty string has a value, but is just empty. Whereas, null refers to nothing (null isn't allocated any memory location hence, pointing to nowhere in memory).

    The s4 variable contains a sequence of characters, s5 is a constant variable of type string whose value can't change throughout the program execution, and the s6 is an array of chars. We do not use the new operator to create a string object it is used only in case of initializing the string with an array of chars. At last, we initialized a path with verbatim (@) string literal (represent a multiline string and a file path).

    The following table shows available string properties and the most commonly used methods in C#.

    Properties Description
    Char It returns a char object at a specified position in the current string object.
    Length It returns the length of a specified string.

    Methods Description
    Compare() It is used to compare two strings and returns integer value as an output.
    Concat() It is used to concatenate the two specified strings.
    Contains() It is used to check whether a specified character/string exists or not in the string value.
    EndsWith() It is used to check whether the specified character is the last character of string or not.
    Equals() It is used to compare two strings. It returns Boolean value as output.
    GetHashCode() It is used to get the HashValue of the specified string.
    IndexOf() It is used to get the index position of the first occurrence of the specified character.
    ToLower() It is used to transform the specified string into the lower case.
    ToUpper() It is used to transform the specified string into upper case.
    Insert() It is used to insert the string/character in the string at the specified position.
    Remove() It is used to delete all the characters from beginning to specified index position.
    Replace() It is used to replace the character.
    Split() It is used to split the string at the specified value.
    StartsWith() It is used to check whether the specified character is the starting character of string or not.
    Substring() It is used to find the substring from a specified string.
    ToCharArray() It is used to convert a string into a char array.
    Trim() It is used to remove the extra whitespaces from the beginning and end of the specified string.


    Following program demonstrate the use of Length and Char properties

    Filename: Program.cs

    using System;
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string s = "Studytonight";
                for (int i = 0; i < s.Length; i++)
                    Console.Write("{0} ", s[i]);
                
                Console.WriteLine(s.Length);
                Console.WriteLine("Studytonight".Length);        
            }
        }
    }

    Output:

    S t u d y t o n i g h t 12
    12

    In the above program, we used the Length property to calculate the length of a string and provided it as a condition to the for loop. The Char property is an indexer in C#, and hence it is used to get each Char object in the given string. On the other hand, we can directly use the Length property on a string without storing in a variable like "Studytonight".Length.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string s1 = "Study";
                string s2 = "tonight     ";
                string s3 = "";
                s3 = string.Concat(s1, s2);
                Console.WriteLine(s3);
                
                if(string.Compare(s1, s2) == 0)
                {
                    Console.WriteLine("Strings are equal.");
                }
                else
                {
                    Console.WriteLine("Strings are unequal");
                }
                
                if(s3.Contains("tonight"))
                {
                    Console.WriteLine("Your specified string found in the original string");
                    string s4 = s3.Replace("tonight", "well");
                    Console.WriteLine(s4);
                }
                
                Console.WriteLine(s3.Trim());
                Console.WriteLine(s3.ToUpper());
                Console.WriteLine(s3.ToLower());
                Console.WriteLine(s3.Substring(5,3));
                
                Console.WriteLine(s3.Remove(5));
                Console.WriteLine(s3.StartsWith("Stud"));
                
            }
        }
    }

    Output:

    Studytonight
    Strings are unequal
    Your specified string found in the original string
    Studywell
    Studytonight
    STUDYTONIGHT
    studytonight
    ton
    Study
    True

    In the above program, we have initialized two strings, s1 = "Study" and s2 = "tonight ". If you observe closely the string s2, then we have given some extra whitespaces at the end of the string. Also, we have created an empty string to store the result of some operation we will be doing on the string s1 and s2. Now, let's see the explanation for each method one by one.

    1. Concat(): this method is used to combine/concatenate the two strings. We have given s1 and s2 and stored the result in s3. After concatenation, the value of s3 is "Studytonight " with a whitespace at the end.

    2. Compare(): this method is used to compare the two strings. In our program, we got the output that the strings are unequal because s1 and s2 contain different string values. In the if statement, we compared the output with 0, as this function returns an integer value and 0 means strings are equal, 1 means the first string is greater than the second string.

    3. Contains(): this method is used to check whether a specified string is available(part of) in an original string value. In our case, we have given tonight, which is present in the string value.

    4. Replace(): this method is used to replace an old string with a new string. In our example, we replaced tonight with well and stored in a new variable s4. Hence, the final output Studywell.

    5. Trim(): this method is used to trim the extra whitespaces available at the start and end of the string. The string s3 contains some extra whitespaces at the end of the string which was removed using this method. If you want to see the actual working of the Trim() method, then give some extra whitespaces at the beginning of a string too, and execute the program to see how it remove the spaces.

    6. ToLower() and ToUpper(): these methods are used to transform the text from lowercase to uppercase and vice versa.

    7. Substring(): this method is used to find a substring from the original specified string. We have provided (5,3), where 5 is starting index and 3 is the length of the substring. The substring index starts from 0. Hence, the output is ton.

    8. Remove(): this method is used to remove the characters from a given string at a specified index. We have provided 5 which means, from index 5, the characters till the end of a string get removed.

    9. StartsWith(): this method is used to check whether an original string value starts with a given string. It returns True if the value match.

    We hope this tutorial helped you to understand the string in C# language.

    About the author:
    Subject Matter Expert of C# Programming at Studytonight.
    Tags:C#C# TutorialC# String
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS