A string is a collection of one or more unicode characters. It is a reference type and hence managed in the Heap memory area.
The System.String class is used to declare string variables. The string keyword which is alias of System.String class can also be used to declare a string variable.
Declare and Initialize a C# String Object
A string object can be declared the same way as any other variable.
Declaration is done as below:
string monthName;
Initialization can be done in various ways. In the below example string objects monthName andyear were assigned string literals and then multiple strings are concatenated and assigned to another string variable yearMonth.
static void Main(string[] args) { string monthName; monthName = "March"; string year; year = "2014"; string separator; separator = ":"; //Concatenate multiple string variables string yearMonth = year + separator + monthName; Console.WriteLine(yearMonth); Console.ReadLine(); }
Output:
String class has some parameter based constructors which can also be used to initialize a string object. String constructor has seven different overloads.
In the below example a character array is passed to the constructor of string month.
static void Main(string[] args) { Char[] monthName = { 'M', 'A', 'Y' }; String month = new String(monthName); Console.WriteLine(month); Console.ReadLine(); }
Output:
May
Verbatim string literals are used to ignore the escape characters. This is useful while assigning file paths or website urls to a string variable.
string fileName = @"C:\Files\Name.txt"; Console.WriteLine(fileName); Console.ReadLine();
Output:
C:\Files\Name.txt
All the examples discussed above are various ways of initializing a string object.
Properties of C# String Class
System.String class has two properties. Both of these are discussed below:
Property | Description |
---|---|
Chars | The Chars property is an indexer which gets the character at a specified position. There is no property with this exact name char in C# instead the indexer([]) is used. |
Length | Returns the length of a string. |
Below an example has been provided to explain the properties of a String class.
class Program { static void Main(string[] args) { string strQuote = "Big house mouse"; //Explains the Char property. Note the use of indexer[]. Console.WriteLine(strQuote[4]); //Usage of length property is shown below Console.WriteLine(strQuote.Length); Console.ReadLine(); } }
Output:
h
15
15
Methods of C# String class
Below we are describing some of the important methods of String class. A complete list of C# methods can be found in the MSDN site .
Method | Description |
---|---|
Compare | Compares two strings and returns a numeric value. A numeric value of zero means the the strings are exact. A negative numeric value means the strings do not match. |
Concat | Concatenates two strings. |
Contains | Checks if one string instance contains another string or not. Returns a boolean True if one string instance contains another or else false. |
Copy | Creates a copy of a string. The copied string is a complete new instance which contains the same characters as the old one. |
EndsWith | Returns a boolean True if a string ends with a specific string or else returnsFalse. |
Equals | Returns a boolean value of True if two strings are equal or else returns False. |
Format | Formats a string and replaces the placeholders with actual string's value. |
IndexOf | Returns the starting index of a string with in another string. The index always starts with zero. |
Insert | Inserts a string with in another string instance at a specified position. |
IsNullOrEmpty | Returns a boolean value of True a string contains a null or empty value or else returns False. |
Join | Joins an array of strings using a separator. |
LastIndexOf | Returns the index of the last occurrence of a character or string that is present with in another string. |
Remove | Removes all the characters starting from a specific position till the end of a string. |
Replace | Replaces a character or a string with another character or string. |
Split | Splits a string using the characters specified in the split method and returns an array containing the substrings. |
StartsWith | Opposite of EndsWith method. Returns a boolean True if a string starts with a specific string or else returns False. |
SubString | Gets a substring from another string starting from a specified index. |
ToCharArray | Converts a string into character array. |
ToLower | Converts all the characters of a string to lower case. |
ToUpper | Converts all the characters of a string to upper case. |
Trim | Trims extra spaces or characters from beginning or end of a string. |
Below example shows the usage of all the methods discussed above (Please use the scroll in the bottom of the below example to view the entire code):
class Program { static void Main(string[] args) { string strOrganization = "Microsoft and Apple"; string strCompanies = "Microsoft and Apple"; //Example of String.Compare method Console.WriteLine("Result of String.Compare method: " + String.Compare(strOrganization, strCompanies)); //Example of String.Concat method string strSearchGiant = "Google:"; Console.WriteLine("Result of String.Concat method: " + String.Concat(strSearchGiant, strCompanies)); //Example of Contains method Console.WriteLine("Result of Contains method: " + strSearchGiant.Contains("oogle")); //Example of String.Copy method string strCopy = string.Copy(strSearchGiant); Console.WriteLine("Result of String.Copy method: " + strCopy); //Example of EndsWith method Console.WriteLine("Result of EndsWith method: " + strSearchGiant.EndsWith("e")); //Example of String.Equals method Console.WriteLine("Result of String.Equals method: " + string.Equals(strSearchGiant, strOrganization)); //Example of String.Format method string strFormattedString = string.Format("I have a {0} house in {1}", "new", "London"); Console.WriteLine("Result of String.Format method: " + strFormattedString); //Example of Insert method Console.WriteLine("Result of Insert method: " + strSearchGiant.Insert(6, "Umbrella")); //Example of String.IsNullOrEmpty method Console.WriteLine("Result of String.IsNullOrEmpty method: " + String.IsNullOrEmpty(strSearchGiant)); //Example of String.Join method string[] strArray = { "A", "B", "C" }; Console.WriteLine("Result of String.Join method: " + String.Join(":", strArray)); //Example of Replace method Console.WriteLine("Result of Replace method: " + strSearchGiant.Replace("o", "i")); //Example of Split method char[] chrArray = { 'g' }; string[] strGoogle = strSearchGiant.Split(chrArray); for (int i = 0; i < strGoogle.Length; i++) { Console.WriteLine("Result of Split method: " + strGoogle[i]); } //Example of StartsWith method Console.WriteLine("Result of StartsWith method: " + strSearchGiant.StartsWith("G")); //Example of Substring method Console.WriteLine("Result of SubString method: " + strSearchGiant.Substring(2)); //Example of ToCharArray method char[] chrArrayFromString = strSearchGiant.ToCharArray(); for (int i=0; i < chrArrayFromString.Length; i++) { Console.WriteLine("Result of ToCharArray method: " + chrArrayFromString[i]); } //Example of ToLower method Console.WriteLine("Result of ToLower method: " + strSearchGiant.ToLower()); //Example of ToUpper method Console.WriteLine("Result of ToUpper method: " + strSearchGiant.ToUpper()); //Example of Trim method char[] chrTrimArray = { 'G' }; Console.WriteLine("Result of Trim method: " + strSearchGiant.Trim(chrTrimArray)); Console.ReadLine(); } }
Output:
Result of String.Compare method: 0
Result of String.Concat method: Google:Microsoft and Apple
Result of Contains method: True
Result of String.Copy method: Google:
Result of EndsWith method: False
Result of String.Equals method: False
Result of String.Format method: I have a new house in London
Result of Insert method: GoogleUmbrella:
Result of String.IsNullOrEmpty method: False
Result of String.Join method: A:B:C
Result of Replace method: Giigle:
Result of Split method: Goo
Result of Split method: le:
Result of StartsWith method: True
Result of SubString method: ogle:
Result of ToCharArray method: G
Result of ToCharArray method: o
Result of ToCharArray method: o
Result of ToCharArray method: g
Result of ToCharArray method: l
Result of ToCharArray method: e
Result of ToCharArray method: :
Result of ToLower method: google:
Result of ToUpper method: GOOGLE:
Result of Trim method: oogle:
Result of String.Concat method: Google:Microsoft and Apple
Result of Contains method: True
Result of String.Copy method: Google:
Result of EndsWith method: False
Result of String.Equals method: False
Result of String.Format method: I have a new house in London
Result of Insert method: GoogleUmbrella:
Result of String.IsNullOrEmpty method: False
Result of String.Join method: A:B:C
Result of Replace method: Giigle:
Result of Split method: Goo
Result of Split method: le:
Result of StartsWith method: True
Result of SubString method: ogle:
Result of ToCharArray method: G
Result of ToCharArray method: o
Result of ToCharArray method: o
Result of ToCharArray method: g
Result of ToCharArray method: l
Result of ToCharArray method: e
Result of ToCharArray method: :
Result of ToLower method: google:
Result of ToUpper method: GOOGLE:
Result of Trim method: oogle: