C# | String

In C#, string is a sequence of Unicode characters or array of characters. The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is an important concept and people gets confused whether the string is a keyword or an object or a class. So let’s clear out this concept.

A string is represented by class System.String. The “string” keyword is an alias for System.String class and instead of writing System.String one can use String which is a shorthand for System.String class. So we can say string and String both can be used as an alias of System.String class. So string is an object of System.String class.

Example:



string s1 = “GeeksforGeeks”; // creating the string using string keyword

String s2 = “GFG”; // creating the string using String class

System.String s3 = “Pro Geek”; // creating the string using String class

The String class is defined in the .NET base class library. In other words a String object is a sequential collection of System.Char objects which represents a string. The maximum size of String object in memory is 2GB or about 1 billion characters. System.String class is immutable, i.e once created its state cannot be altered.

Program: To illustrate how to declare the string and initialize the string. Also, below program show the declaration and initialization of a string in a single line.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to declare string using
// string, String and System.String
// and initialization of string
using System;
class Geeks {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // declare a string Name using 
        // "System.String" class
        System.String Name;
          
        // initialization of String
        Name = "Geek";
  
  
        // declare a string id using 
        // using an alias(shorthand) 
        // "String" of System.String
        // class
        String id;
          
        // initialization of String
        id = "33";
  
        // declare a string mrk using 
        // string keyword
        string mrk;
          
        // initialization of String
        mrk = "97";
          
        // Declaration and initialization of
        // the string in a single line
        string rank = "1";
  
        // Displaying Result
        Console.WriteLine("Name: {0}", Name);
        Console.WriteLine("Id: {0}", id);
        Console.WriteLine("Marks: {0}", mrk);
        Console.WriteLine("Rank: {0}", rank);
    }
}

chevron_right


Output:

Name: Geek
Id: 33
Marks: 97
Rank: 1

String Characteristics:

  • It is a reference type.
  • It’s immutable( its state cannot be altered).
  • It can contain nulls.
  • It overloads the operator(==).

Differences between String and System.String :
The string is an alias for System.String. Both String and System.String means same and it will not affect the performance of the application. “string” is keyword in C#. So the main difference comes in the context, how to use these:

  • The String is used for the declaration but System.String is used for accessing static string methods.
  • The String is used to declare fields, properties etc. that it will use the predefined type System.String. It is the easy way to use.
  • The String has to use the System.String class methods, such as String.SubString, String.IndexOf etc. The string is only an alias of System.String.

Note: In .NET, the text is stored as a sequential collection of the Char objects so there is no null-terminating character at the end of a C# string. Therefore a C# string can contain any number of embedded null characters (‘\0’).

String arrays: We can also create the array of string and assigns values to it. The string arrays can be created as follows:


  • Syntax:
    String [] array_variable  =  new  String[Length_of_array]
  • Example: To illustrate the creation of string arrays and assigning values to it
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program for an array of strings
    using System;
    class Geeks {
          
    // Main Method
    static void Main(string[] args)
    {
      
        String[] str_arr = new String[3];
      
        // Initialising the array of strings
        str_arr[0] = "Geeks";
        str_arr[1] = "For";
        str_arr[2] = "Geeks";
          
        // printing String array
        for(int i = 0; i < 3; i++)
        {
            Console.WriteLine("value at Index position "+i+" is "+str_arr[i]);
        }
      
    }
    }

    chevron_right

    
    

    Output:

    value at Index position 0 is Geeks
    value at Index position 1 is For
    value at Index position 2 is Geeks
    

Reading String from User-Input: A string can be read out from the user input. ReadLine() method of console class is used to read a string from user input.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to demonstrate Reading 
    // String from User-Input
    using System;
    class Geeks {
          
        // Main Method
        static void Main(string[] args)
        {
      
            Console.WriteLine("Enter the String");
          
            // Declaring a string object read_user 
            // and taking the user iput using 
            // ReadLine() method
            String read_user = Console.ReadLine();
          
            // Displaying the user input
            Console.WriteLine("User Entered: " + read_user);
      
        }
          
    }

    chevron_right

    
    

Input:

Hello Geeks !

Output:

Enter the String
User Entered: Hello Geeks !

Different Ways for Creating a String:

  • Create a string from a literal
  • Create a string using concatenation
  • Create a string using a constructor
  • Create a string using a property or a method
  • Create a string using formatting

Create a string from a literal: It is the most common way to create a string. In this, a user has to define string variable and then assign the value within the double quotes. We can use any type of characters within double quotes except some special character like a backslash (\).

  • Program: To illustrate the string creation using literals
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to demonstarte the
    // string creation using literals
    using System;
    class Geeks {
      
        // Main Method
        static void Main(string[] args)
        {
            string str1 = "GeeksforGeeks";
            Console.WriteLine(str1);
      
            // Give Error Unrecognized escape sequence \H, \G, \p
            // string str3 = "X:\Home\GFG\Geeks.cs";
            // Console.WriteLine(str3);
      
            // using double slash \\ 
            string str2 = "X:\\Home\\GFG\\program.cs";
            Console.WriteLine(str2);
      
        }
    }

    chevron_right

    
    

    Output:

    GeeksforGeeks
    X:\Home\GFG\program.cs
    

Create a string using concatenation: We can create a string by using string concatenation operator “+” in C#. To create a single string from any combination of String instances and string literals, the string concatenation operator (+) is used to combine or merge one or more string.

  • Program: To illustrates the use of the string concatenation operator
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to demonstrate the use of
    // the string concatenation operator.
    using System;
    class Geeks {
      
        // Main Method
        public static void Main()
        {
            string s1 = "Geek";
            string s2 = "s";
            string s3 = "For";
            string s4 = "Geek";
      
            // using concatenation operator
            string str = s1 + s2 + s3 + s4 + "s";
      
            Console.WriteLine(str);
        }
    }

    chevron_right

    
    

    Output:


    GeeksForGeeks
    

Create a string using Constructor: The String class has been several overloaded constructors which take an array of characters or bytes. Some of the constructors include pointers to character arrays or signed byte arrays as parameters.

  • Program: To illustrates Creation of a string using the constructor
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to demonstrate the creation 
    // of string using the constructor
    using System;
    class Geeks {
          
        // Main Method
        public static void Main()
        {
            char[] chars = { 'G', 'E', 'E', 'K', 'S' };
      
            // Create a string from a character array.
            string str1 = new string(chars);
            Console.WriteLine(str1);
      
            // Create a string that consists of 
            // a character repeated 20 times.
            string str2 = new string('G', 10);
            Console.WriteLine(str2);
      
            /* below comment part give the error 
               for unsafe mode go through offline
               sbyte[] bytes = { 0x41, 0x42, 0x43,
               0x44, 0x45, 0x00 };
               string stringtoBytes = null;
               string stringtomChars = null;
                unsafe
                {
                    fixed (sbyte* pbytes = bytes)
                    {
                      
                        // Create a string from a pointer
                        // to a signed byte array.
                        stringFromBytes = new string(pbytes);
                    }
                          
                    fixed (char* pchars = chars)
                    {
                      
                        // Create a string from a pointer
                        // to a character array.
                        stringFromChars = new string(pchars);
                    }
                }
              
                Console.WriteLine(stringtoBytes); // output : ABCDE
                Console.WriteLine(stringtoChars); // output : GEEKS */
          
        }
    }

    chevron_right

    
    

    Output:

    GEEKS
    GGGGGGGGGG
    

Create a string using a Property or a Method: To retrieving a property or calling a method which always returns a string. For example, using methods of the String class to extract a substring from a larger string.

  • Program: To illustrate the Creation of a string using a Property or a Method
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to extract a substring from a larger
    // string using methods of the String class
    using System;
    class Geeks {
      
        // Main Method
        public static void Main()
        {
            string sentence = "Geeks For Geeks";
      
            // Extract the second word.
      
            // taking the first space position value
            int startpos = sentence.IndexOf(" ") + 1;
      
            // taking the second space position value
            int endpos = sentence.IndexOf(" ", startpos) - startpos;
      
            // now extract second word from the sentence
            string wrd = sentence.Substring(startpos, endpos);
      
            Console.WriteLine(wrd);
        }
    }

    chevron_right

    
    

    Output:

    For
    

Create a string using Format: The “Format” method is used to convert the value or object to its string representation. The String.Format method returns a string.

  • Program: To illustrate the creation of string using Format method
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# method to illustrate the creation 
    // of string using format method
    using System;
    class Geeks {
      
        // Main Method
        public static void Main()
        {
            int no = 10;
            string cname = "BMW";
            string clr = "Red";
      
            // string creation using string.Format method
            string str = string.Format("{0} {1} Cars color " +
                         "are {2}", no.ToString(), cname, clr);
            Console.WriteLine(str);
        }
    }

    chevron_right

    
    

    Output:

    10 BMW Cars color are Red
    

String Class Properties: The String class has two properties as follows:

  1. Chars: It is used to get the Char object at a specified position in the current String object.
  2. Length: It is used to get the number of characters in the current String object. To know more about the string class properties please go to String Properties in C#.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shubham_singh



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.