C# String

String in C# is a sequence of Unicode characters or maybe it can be an array of characters. To represent String in C# we use a class named System. The string keyword is an alias for the System.String class. String in C# represents the array of characters (known as text). The string is a reference type. It can contain nulls. It also overloads the operator(==).

Consider this Example to understand:

Creating an Object of String in C#:

There are some methods to create string objects.

  1. Create string by using a String class constructor.
  2. Create string by assigning a string literal to a String variable.
  3. Create string by using the string concatenation operator (+).
  4. Create string by retrieving a property or calling a method that returns a string.
  5. Create string by calling a formatting method to convert a value or an object to its string representation.

//C# program for an array of strings

using System;
public class Geeks {
     
// Main Method
public static void Main(string[] args)
{
 
    String[] str_arr = new String[2];
 
    //Initialising the strings array
    str_arr[0] = "String";
    str_arr[1] = "Array";
     
    //printing String array
    for(int i = 0; i < 2; i++)
    {
        Console.WriteLine("The Value at Index"+i+" is "+str_arr[i]);
    }
 
}
}
There are 2 main Properties of string in C#.
  • Length: This property gets the number of characters in the current String object.
  • Chars: This property gets the Char object at a specified position in the current String object.
There are different ways of creating a string in C#, as given below: 
  1. Create a string from a literal
  2. Create a string using formatting
  3. Create a string using a constructor
  4. Create a string using concatenation
  5. Create a string using a property or a method

MethodDescription
Clone()It returns a reference to this instance of String.
Compare(String, String)It compares two specified String objects and returns an integer that indicates their relative position in the sort order.
Concat(String, String)It concatenates two specified instances of String.
Contains(String)It returns a value indicating whether a specified substring occurs within this string.
Copy(String)It creates a new instance of String with the same value as a specified String.
Format(String, Object)It replaces one or more format items in a specified string with the string representation of a specified object.
Trim()It removes all leading and trailing white-space characters from the current String object.
ToLower()It converts a given string to a lowercase.
ToUpper()It converts a given string to uppercase.
Split(Char[])It splits a string into substrings that are based on the characters in an array.
Substring(Int32)It retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.