In C#, a string is used to store text. It represents a sequence of characters and is one of the most commonly used reference types.
Strings in C# are immutable, which means their value cannot be changed once created.
// String declaration
string name = "Rahul";
string message = "Welcome to C#";
| Method | Description | Example |
|---|---|---|
| Length | Returns string length | name.Length |
| ToUpper() | Converts to uppercase | name.ToUpper() |
| ToLower() | Converts to lowercase | name.ToLower() |
| Trim() | Removes extra spaces | name.Trim() |
| Substring() | Extracts part of string | name.Substring(0, 3) |
| Replace() | Replaces text | message.Replace("C#", "DotNet") |
| Contains() | Checks text existence | message.Contains("C#") |
string text = " Hello World ";
Console.WriteLine(text.Length);
Console.WriteLine(text.Trim());
Console.WriteLine(text.ToUpper());
Console.WriteLine(text.Substring(2, 5));
Combining strings together.
string firstName = "Rahul";
string lastName = "Sharma";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
A cleaner way to format strings using $.
int age = 25;
Console.WriteLine($"My age is {age}");
Strings play a vital role in handling text data in C#. Understanding string methods and formatting techniques helps in writing clean and efficient code.