Scroll To Top
Reader Level:
Article
String in C#

String in C#

By Mahesh Chand on Feb 05, 2003
In this article, you will learn how to work with strings in C#. The article discusses the String class, its methods and properties and how to use them.

Strings are one of the most important data types in any modern language including C#. In this article, you will learn how to work with strings in C#. The article discusses the String class, its methods and properties and how to use them.
 
Introduction

In any programming language, to represent a value, we need a data type. The Char data type represents a character in .NET. In .NET, text is stored as a sequential read-only collection of Char objects. 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').

The System.String data type is used to represent a string in .NET. A string in C# is an object of type System.String.

The String class in C# represents a string.

The following code creates three strings with a name, number and double values.

  1. // String of characters  
  2. System.String authorName = "Mahesh Chand";  
  3.   
  4. // String made of an Integer  
  5. System.String age = "33";  
  6.   
  7. // String made of a double  
  8. System.String numberString = "33.23"

Here is the complete example that shows how to use stings in C# and .NET.

  1. using System;  
  2. namespace CSharpStrings  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             // Define .NET Strings  
  9.             // String of characters  
  10.             System.String authorName = "Mahesh Chand";  
  11.   
  12.             // String made of an Integer  
  13.             System.String age = "33";  
  14.   
  15.             // String made of a double  
  16.             System.String numberString = "33.23";  
  17.   
  18.             // Write to Console.  
  19.             Console.WriteLine("Name: {0}", authorName);  
  20.             Console.WriteLine("Age: {0}", age);  
  21.             Console.WriteLine("Number: {0}", numberString);  
  22.             Console.ReadKey();  
  23.         }  
  24.     }  

String Class

The string class defined in the .NET base class library represents text as a series of Unicode characters. The String class provides methods and properties to work with strings.

The String class has methods to clone a string, compare strings, concatenate strings, and copy strings. This class also provides methods to find a substring in a string, find the index of a character or substring, replace characters, spilt a string, trim a string, and add padding to a string. The string class also provides methods to convert a string characters to uppercase or lowercase.

Check out these links to learn about a specific operation or functionality of strings.

What is different between String and System.String?

.NET defines all data types as a class. The System.String class represents a collection of Unicode characters also known as a text. The System.String class also defines the properties and methods to work with string data types.

The String class is equivalent to the System.String in C# language. The string class also inherits all the properties and methods of the System.String class.

Create a string

There are several ways to construct strings in C# and .NET.
  • Create a string using a constructor
  • Create a string from a literal
  • Create a string using concatenation
  • Create a string using a property or a method
  • Create a string using formatting
Create a string using its constructor

The String class has several overloaded constructors that take an array of characters or bytes. The following code snippet creates a string from an array of characters.
  1. char[] chars = { 'M''a''h''e''s''h' };  
  2. string name = new string(chars);  
  3. Console.WriteLine(name);  
Create a string from a literal

This is the most common ways to instantiate a string.

You simply define a string type variable and assign a text value to the variable by placing the text value without double quotes. You can put almost any type of characters within double quotes accept some special character limitations.

The following code snippet defines a string variable named firstName and then assigns text value Mahesh to it.
  1. string firstName;  
  2. firstName = "Mahesh";  
Alternatively, we can assign the text value direct to the variable.
  1. string firstName = "Mahesh";  
Here is a complete sample example of how to create strings using literals.

  1.  
  2. using System;  
  3. namespace CSharpStrings  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             string firstName = "Mahesh";  
  10.             string lastName = "Chand";  
  11.             string age = "33";  
  12.             string numberString = "33.23";   
  13.             Console.WriteLine("First Name: {0}", firstName);  
  14.             Console.WriteLine("Last Name: {0}", lastName);  
  15.             Console.WriteLine("Age: {0}", age);  
  16.             Console.WriteLine("Number: {0}", numberString);  
  17.             Console.ReadKey();  
  18.         }   
  19.     }  

Create a string using concatenation

Sting concatenation operator (+) can be used to combine more than one string to create a single string. The following code snippet creates two strings. The first string adds a text Date and current date value from the DateTime object. The second string adds three strings and some hard coded text to create a larger string.
  1. string nowDateTime = "Date: " + DateTime.Now.ToString("D");  
  2. string firstName = "Mahesh";  
  3. string lastName = "Chand";  
  4. string age = "33";  
  5. string authorDetails = firstName + " " + lastName + " is " + age + " years old.";  
  6.   
  7. Console.WriteLine(nowDateTime);  
  8. Console.WriteLine(authorDetails); 
Create a string using a property or a method

Some properties and methods of the String class returns a string object such as SubString method. The following code snippet takes one sentence string and finds the age within that string. The code returns 33.
  1. string authorInfo = "Mahesh Chand is 33 years old.";  
  2. int startPosition = sentence.IndexOf("is ") + 1;  
  3. string age = authorInfo.Substring(startPosition +2, 2 );  
  4. Console.WriteLine("Age: " + age); 
 Create a string with Format

The String.Format method returns a string. The following code snippet creates a new string using the Format method.
  1. string name = "Mahesh Chand";  
  2. int age = 33;  
  3. string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString());  
  4. Console.WriteLine(authorInfo); 
Create a string using ToString Method

The ToString method returns a string. We can apply ToString on pretty much any data type that can be converted to a string. The following code snippet converts an int data type to a string.
  1. string name = "Mahesh Chand";  
  2. int age = 33;  
  3. string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString());  
  4. Console.WriteLine(authorInfo); 
 Get all characters of a string using C#

A string is a collection of characters.

The following code snippet reads all characters of a string and displays on the console.
  1. string nameString = "Mahesh Chand";  
  2. for (int counter = 0; counter <= nameString.Length - 1; counter++)  
  3. Console.WriteLine(nameString[counter]); 
Size of string

The Length property of the string class returns the number of characters in a string including white spaces.

The following code snippet returns the size of a string and displays on the console.
  1. string nameString = "Mahesh Chand";  
  2. Console.WriteLine(nameString);  
  3. Console.WriteLine("Size of string {0}", nameString.Length); 
Number of characters in a string

We can use the string.Length property to get the number of characters of a string but it will also count an empty character. So, to find out exact number of characters in a string, we need to remove the empty character occurrences from a string.

The following code snippet uses the Replace method to remove empty characters and then displays the non-empty characters of a string.
  1. string name = "Mahesh Chand";  
  2.   
  3. string name = "Mahesh Chand";  
  4.   
  5. // Get size of string  
  6. Console.WriteLine("Size of string: {0}", name.Length );  
  7.   
  8. // Remove all empty characters  
  9. string nameWithoutEmptyChar = name.Replace(" """);  
  10.   
  11. // Size after empty characters are removed  
  12. Console.WriteLine("Size of non empty char string: {0}", nameWithoutEmptyChar.Length);  
  13.   
  14. // Read and print all characters  
  15. for (int counter = 0; counter <= nameWithoutEmptyChar.Length - 1; counter++)  
  16. Console.WriteLine(nameWithoutEmptyChar[counter]); 
Convert String to Char Array

ToCharArray method converts a string to an array of Unicode characters. The following code snippet converts a string to char array and displays them.
  1. string sentence = "Mahesh Chand is an author and founder of C# Corner";  
  2. char[] charArr = sentence.ToCharArray();  
  3. foreach (char ch in charArr)  
  4. {  
  5.   Console.WriteLine(ch);  
  6. }  
 Empty String

An empty string is a valid instance of a System.String object that contains zero characters. There are two ways to create an empty string. We can either use the string.Empty property or we can simply assign a text value with no text in it.

The following code snippet creates two empty strings.
  1. string empStr = string.Empty;  
  2. string empStr2 = ""
Both of the statements above generates the same output.
 
An empty string is sometimes used to compare the value of other strings. The following code snippet uses an empty string to compare with the name string.
  1. string name = "Mahesh Chand";  
  2. if (name != empStr)  
  3. {  
  4.   Console.WriteLine(name);  

In real world coding, we will probably never create an empty string unless you plan to use it somewhere else as a non-empty string. We can simply use the string.Empty direct to compare a string with an empty string.
  1. if (name != string.Empty)  
  2. {  
  3.   Console.WriteLine(name);  

Here is a complete example of using an empty string.
  1. string empStr = string.Empty;  
  2. string empStr2 = "";  
  3. string name = "Mahesh Chand";  
  4. if (name != empStr)  
  5. {  
  6.   Console.WriteLine(name);  
  7. }  
  8. if (name != string.Empty)  
  9. {  
  10.   Console.WriteLine(name);  

Null String

A null string is a string variable that has not been initialized yet and has a null value. If you try to call any methods or properties of a null string, you will get an exception. A null string valuable is exactly same as any other variable defined in your code.

A null string is typically used in string concatenation and comparison operations with other strings.

The following code example shows how to use a null string.
  1. string nullStr = null;  
  2. string empStr = string.Empty;  
  3. string name = "Mahesh Chand";  
  4.   
  5. if ((name != nullStr) || (name != empStr))  
  6. {  
  7.   Console.WriteLine(name + " is neither null nor empty");  

Summary

In this article, we learned basics of strings in C# and .NET and how to use the String class available in .NET in our code. I've written a 20 page e-book just on working with strings in .NET. The book contains almost every method and property and how to use them. 

Download Free E-book for the full C# Strings article