In C#, a string is a sequence of characters that represents text. In code, a string is declared using the string keyword, followed by a variable name and an optional initial value. Here's an example:
string greeting = "Hello, world!";
In this example, greeting is a variable of type string that has an initial value of "Hello, world!".
You can perform various operations on strings in C#, such as concatenation, trimming, and formatting. This tutorial teaches you fundamentals of string data type in C# and how to perform various operations on strings in C#.
C# string Class
In C#, the string class is a built-in class that represents a string of characters. It is part of the System namespace and is used extensively in C# programming for working with text.
The string class provides a wide range of methods and properties that you can use to manipulate and work with strings. Some of the commonly used methods and properties of the string class include:
- Length: returns the length of the string
- IndexOf: finds the index of a specified character or substring in the string
- Substring: returns a substring of the string
- ToLower and ToUpper: convert the string to lowercase or uppercase
- Replace: replaces a specified character or substring with another character or substring
- Trim: removes any leading or trailing whitespace characters from the string
- Split: splits the string into an array of substrings based on a specified delimiter character or substring
Here's an example that shows how to use some of these methods:
string text = " Hello, world! ";
int length = text.Length; // length = 17
int index = text.IndexOf("world"); // index = 8
string subString = text.Substring(3, 7); // subString = "lo, wor"
string upperCaseText = text.ToUpper(); // upperCaseText = " HELLO, WORLD! "
string replacedText = text.Replace("world", "everyone"); // replacedText = " Hello, everyone! "
string[] words = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
// words = { "Hello", "world!" }
string trimmedText = text.Trim(); // trimmedText = "Hello, world!"
As you can see, the string class provides a rich set of methods and properties that you can use to work with strings in your C# code.
What is different between String and System.String?
The System.String class represents a collection of Unicode characters also known as text. The System.String class also defines the properties and methods to work with string data types.
The String class is an alias to System.String class in .NET. The String class inherits all the properties and methods of the System.String class.
How to create a string in C#?
There are several ways to construct strings in C#.
- 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 C# 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.
char[] chars = { 'M', 'a', 'h', 'e', 's', 'h' };
string name = new string(chars);
Console.WriteLine(name);
Create a string from a literal in C#
This is the most common way 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 character within double quotes accept some special character limitations.
The following code snippet defines a string variable named firstName and then assigns the text value Mahesh to it.
string firstName;
firstName = "Mahesh";
Alternatively, we can assign the text value directly to the variable.
string firstName = "Mahesh";
Here is a complete example of how to create strings using literals.
using System;
namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
string numberString = "33.23";
Console.WriteLine("First Name: {0}", firstName);
Console.WriteLine("Last Name: {0}", lastName);
Console.WriteLine("Age: {0}", age);
Console.WriteLine("Number: {0}", numberString);
Console.ReadKey();
}
}
}
Create a string using concatenation
String concatenation operators (+) 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.
string nowDateTime = "Date: " + DateTime.Now.ToString("D");
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
string authorDetails = firstName + " " + lastName + " is " + age + " years old.";
Console.WriteLine(nowDateTime);
Console.WriteLine(authorDetails);
Here is a detailed article on string concatenation - Six Effective Ways To Concatenate Strings In C#.
Create a string using a property or a method
Some properties and methods of the String class return a string object such as the SubString method. The following code snippet takes one sentence string and finds the age within that string. The code returns 33.
string authorInfo = "Mahesh Chand is 33 years old.";
int startPosition = sentence.IndexOf("is ") + 1;
string age = authorInfo.Substring(startPosition +2, 2 );
Console.WriteLine("Age: " + age);
Create a string using Format
The String.Format method returns a string. The following code snippet creates a new string using the Format method.
string name = "Mahesh Chand";
int age = 33;
string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString());
Console.WriteLine(authorInfo);
UPDATED: C# 6 introduced string interpolation, which is a new and modern way of concatenating, formatting, and manipulating strings. This is the recommended method to format strings.
String interpolation is a String Interpolation in C#.
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.
string name = "Mahesh Chand";
int age = 33;
string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString());
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 them on the console.
string nameString = "Mahesh Chand";
for (int counter = 0; counter <= nameString.Length - 1; counter++)
Console.WriteLine(nameString[counter]);
Get the size of a string in C#
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 it on the console.
string nameString = "Mahesh Chand";
Console.WriteLine(nameString);
Console.WriteLine("Size of string {0}", nameString.Length);
Get the number of characters in a C# string
We can use the string.Length property to get the number of characters of a string but it will also count as an empty character. So, to find out the 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.
string name = "Mahesh Chand";
string name = "Mahesh Chand";
// Get size of string
Console.WriteLine("Size of string: {0}", name.Length );
// Remove all empty characters
string nameWithoutEmptyChar = name.Replace(" ", "");
// Size after empty characters are removed
Console.WriteLine("Size of non empty char string: {0}", nameWithoutEmptyChar.Length);
// Read and print all characters
for (int counter = 0; counter <= nameWithoutEmptyChar.Length - 1; counter++)
Console.WriteLine(nameWithoutEmptyChar[counter]);
How to convert a C# string to char array
The ToCharArray method converts a string into an array of Unicode characters. The following code snippet converts a string to a char array and displays them.
string sentence = "Mahesh Chand is an author and founder of C# Corner";
char[] charArr = sentence.ToCharArray();
foreach (char ch in charArr)
{
Console.WriteLine(ch);
}
What is an empty string in C#?
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.
string empStr = string.Empty;
string empStr2 = "";
Both of the above statements generate 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.
string name = "Mahesh Chand";
if (name != empStr)
{
Console.WriteLine(name);
}
In real-world coding, we will probably never create an empty string, unless we plan to use it somewhere else as a non-empty string. We can simply use the string.Empty direction to compare a string to an empty string.
if (name != string.Empty)
{
Console.WriteLine(name);
}
Here is a complete example of using an empty string.
string empStr = string.Empty;
string empStr2 = "";
string name = "Mahesh Chand";
if (name != empStr)
{
Console.WriteLine(name);
}
if (name != string.Empty)
{
Console.WriteLine(name);
}
How to use null strings in C#?
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 the 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.
string nullStr = null;
string empStr = string.Empty;
string name = "Mahesh Chand";
if ((name != nullStr) || (name != empStr))
{
Console.WriteLine(name + " is neither null nor empty");
}
Summary
This tutorial taught you how to use strings in C#.