Open In App

C# | String class

Last Updated : 23 Jan, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

In C#, a 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 represented by a class System.String.
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 represent a string. The maximum size of the String object in memory can be 2GB or about 1 billion characters.

Characteristics of String Class:

  • The System.String class is immutable, i.e once created its state cannot be altered.
  • With the help of length property, it provides the total number of characters present in the given string.
  • String objects can include a null character which counts as the part of the string’s length.
  • It provides the position of the characters in the given string.
  • It allows empty strings. Empty strings are the valid instance of String objects that contain zero characters.
  • A string that has been declared but has not been assigned a value is null. Attempting to call methods on that string throws a NullReferenceException.
  • It also supports searching strings, comparison of string, testing of equality, modifying the string, normalization of string, copying of strings, etc.
  • It also provides several ways to create strings like using a constructor, using concatenation, etc.

Constructor

Constructor Description
String(Char*) Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters.
String(Char*, Int32, Int32) Initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length.
String(Char, Int32) Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.
String(Char[]) Initializes a new instance of the String class to the value indicated by an array of Unicode characters.
String(Char[], Int32, Int32) Initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length.
String(SByte*) Initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers.
String(SByte*, Int32, Int32) Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length.
String(SByte*, Int32, Int32, Encoding) Initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object.

Example:




// 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 5 times.
        string str2 = new string('E', 5);
        Console.WriteLine(str2);
    }
}


Output:

GEEKS
EEEEE

Properties

Property Description
Chars[Int32] Gets the Char object at a specified position in the current String object.
Length Gets the number of characters in the current String object.

Example:




// C# program to demonstrate the
// String Class Properties
using System;
  
class Geeks {
   
    // Main Method
    public static void Main()
    {
        string str = "GeeksforGeeks";
          
        // using Chars[Int32] & Length property
        for (int i = 0; i <= str.Length - 1; i++)
            Console.Write("{0} ", str[i]);
    }
}


Output:

G e e k s f o r G e e k s

Methods

Method Description
Clone() Returns a reference to this instance of String.
Compare() Used to compare the two string objects.
CompareOrdinal(String, Int32, String, Int32, Int32) Compares substrings of two specified String objects by evaluating the numeric values of the corresponding Char objects in each substring.
CompareOrdinal(String, String) Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string.
CompareTo() Compare the current instance with a specified Object or String object.
Concat() Concatenates one or more instances of String, or the String representations of the values of one or more instances of Object.
Contains(String) Returns a value indicating whether a specified substring occurs within this string.
Copy(String) Creates a new instance of String with the same value as a specified String.
CopyTo(Int32, Char[], Int32, Int32) Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.
EndsWith() Determines whether the end of this string instance matches a specified string.
Equals() Determines whether two String objects have the same value.
Format() Converts the value of objects to strings based on the formats specified and inserts them into another string.
GetEnumerator() Retrieves an object that can iterate through the individual characters in this string.
GetHashCode() Returns the hash code for this string.
GetType() Gets the Type of the current instance.
(Inherited from Object)
GetTypeCode() Returns the TypeCode for class String.
IndexOf() Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.
IndexOfAny() Reports the index of the first occurrence in this instance of any character in a specified array of Unicode characters. The method returns -1 if the characters in the array are not found in this instance.
Insert(Int32, String) Returns a new string in which a specified string is inserted at a specified index position in this instance.
Intern(String) Retrieves the system’s reference to the specified String.
IsInterned(String) Retrieves a reference to a specified String.
IsNormalized() Indicates whether this string is in a particular Unicode normalization form.
IsNullOrEmpty(String) Indicates whether the specified string is null or an Empty string.
IsNullOrWhiteSpace(String) Indicates whether a specified string is null, empty, or consists only of white-space characters.
Join() Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.
LastIndexOf() Reports the zero-based index position of the last occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.
MemberwiseClone() Creates a shallow copy of the current Object.
(Inherited from Object)
Normalize() Returns a new string whose binary representation is in a particular Unicode normalization form.
PadLeft() Returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character.
PadRight() Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.
Remove() Returns a new string in which a specified number of characters from the current string are deleted.
Replace() Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.
Split() Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.
StartsWith(String) Determines whether the beginning of this string instance matches a specified string.
Substring(Int32) Retrieves a substring from this instance.
ToCharArray() Copies the characters in this instance to a Unicode character array.
ToLower() Returns a copy of this string converted to lowercase.
ToLowerInvariant() Returns a copy of this String object converted to lowercase using the casing rules of the invariant culture.
ToString() Converts the value of this instance to a String.
ToUpper() Returns a copy of this string converted to uppercase.
ToUpperInvariant() Returns a copy of this String object converted to uppercase using the casing rules of the invariant culture.
Trim() Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.
TrimEnd(Char[]) Removes all trailing occurrences of a set of characters specified in an array from the current String object.
TrimStart(Char[]) Removes all leading occurrences of a set of characters specified in an array from the current String object.

Example:




// C# program to illustrate
// String class methods
using System;
   
class GFG {
      
    static void copymethod()
    {
        string str1 = "GeeksforGeeks";
        string str2 = "geeks";
        Console.WriteLine("Original Strings: str1 = "
                              + "'{0}' and str2 ='{1}'",
                          str1, str2);
   
        Console.WriteLine("");
   
        Console.WriteLine("After Copy method");
        Console.WriteLine("");
   
        // using the Copy method
        // to copy the value of str1
        // into str2
        str2 = String.Copy(str1);
   
        Console.WriteLine("Strings are str1 = "
                              + "'{0}' and str2='{1}'",
                          str1, str2);
    }
      
   
    // Main method
    static public void Main()
    {
   
        // variables
        string str1 = "geeksforgeeks";
        string str2 = "geeksforgeeks";
   
        bool result;
   
        // Compare(string, string) method return true
        // because the given strings are equal
        result = String.Compare(str1, str2) == 0;
   
        Console.WriteLine("Result of Compare Method: " +result);
          
        // calling method
        copymethod();
    }
}


Output:

Result of Compare Method: True
Original Strings: str1 = 'GeeksforGeeks' and str2 ='geeks'

After Copy method

Strings are str1 = 'GeeksforGeeks' and str2='GeeksforGeeks'

Operators

Operator Description
Equality(String, String) Determines whether two specified strings have the same value.
Inequality(String, String) Determines whether two specified strings have different values.

Example:




// C# program to illustrate the
// Equality and Inequality operator
using System;
  
class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = "WelcomeToGeeks";
        string s2 = "WelcomeToGeeks";
        bool result1, result2;
  
        // Equality operator return true
        // as both string are equal
        result1 = s1 == s2;
  
        // Inequality operator return false
        // as both string are equal
        result2 = s1 != s2;
  
        Console.WriteLine(result1);
        Console.WriteLine(result2);
    }
}


Output:

True
False

Reference:



Previous Article
Next Article

Similar Reads

C# Program to Check a Class is a Sub-Class of a Specified Class or Not
A class is a collection of methods, variables, and objects. A subclass is a class that is extended from the parent class. It should achieve all the properties from the parent class. Its syntax is similar to a class. Using: operator we can create the subclass. We can check the class is a subclass of the specific class or not by using the IsSubclassO
2 min read
File.Replace(String, String, String) Method in C# with Examples
File.Replace(String, String, String) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file and creates a backup of the replaced file.Syntax: public static void Replace (string sourceFileName, string destinationFileName, string destinati
3 min read
File.Replace(String, String, String, Boolean) Method in C# with Examples
File.Replace(String, String, String, Boolean) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file, creates a backup of the replaced file, and optionally ignores merge errors. Syntax: public static void Replace (string sourceFileName,
3 min read
C# Program to Check a Specified class is a Serializable class or not
Serialization is a method of converting an object into a stream of bytes that will be used to store the object in the database, or memory, or file, etc so that we can easily read back and convert it back to an object. So to check whether a specified class is serializable or not we use the IsSerializable property of the Type class. It will return tr
2 min read
C# Program to Inherit an Abstract Class and Interface in the Same Class
Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must imp
3 min read
C# Program to Check a Specified Class is an Abstract Class or Not
Abstraction is the process to hide the internal details and showing only the functionality. The abstract keyword is used before the class or method to declare the class or method as abstract. In this article, we will learn how to check a specified class is an abstract class or not. To do this task we use the IsAbstract property of the Type class. T
2 min read
C# Program to Check a Specified Class is a Sealed Class or not
A Sealed class is a class that will not let the users inherit the class. We can create a sealed class using sealed keywords. This keyword tells the compiler that the class is a sealed class. In this article, we will learn how to check the specified class is a sealed class or not. So we use the IsSealed property of the Type class. This property is u
2 min read
C# | How to get TypeCode for the class String
GetTypeCode() method is used to get the TypeCode of the specified string. Here TypeCode enum represents a specific type of object. In TypeCode every data type is represented by a specific number like String is represented by 18, Int32 is represented by 9, etc. Syntax: public TypeCode GetTypeCode (); Return value: This method return an enumerated co
2 min read
C# | Equals(String, String) Method
In C#, Equals(String, String) is a String method. It is used to determine whether two String objects have the same value or not. Basically, it checks for equality. If both strings have the same value, it returns true otherwise returns false. This method is different from Compare and CompareTo methods. This method compares two string on the basis of
2 min read
C# | How to copy a String into another String
String.Copy(String) Method is used to create a new instance of String with the same value as a specified String. In other words, this method is used to copy the data of one string into a new string. The new string contains same data like an original string but represents a different object reference. Syntax: public static string Copy (string value)
2 min read
Article Tags :