C# - Strings


In C# string is a datatype. String is a sequence of characters represented the ‘string’ data type.

String is a immutable data type which means their value cannot be changed after they created.

Here are some operations and examples we can perform on string data type.

We can create a string in several ways:

Using Double Quotes

string myString = "Hello, World!";

Using the String Constructor

string anotherString = new string('a', 5); // Creates a string with 'a'

String Concatenation

String concatenation used to combine two string using ‘+’ operator.

string firstName = "John"; 
string lastName = "Doe"; 
string fullName = firstName + " " + lastName; // Concatenation using + 
string anotherFullName = string.Concat(firstName, " ", lastName); // Concatenation using Concat method

String Length

String length property gives you the characters count of string.

string str = "Hello!"; 
int length = str.Length; // length will be 6

Accessing Characters

You can access individual characters in a string using indexing:

string text = "Example"; 
char firstChar = text[0]; // Accessing the first character 'E'

String Methods

C# provides build-in methods to manipulate the string data such as ToUpper(), ToLower(), Substring(), Replace(), Split(), etc.

string sentence = "This is a sample sentence."; 
string upperCase = sentence.ToUpper(); // Converts the string to uppercase 
string replaced = sentence.Replace("sample", "different"); // Replaces "sample" with "different" 
string[] words = sentence.Split(' '); // Splits the sentence into an array of words

String Interpolation

String interpolation allows embedding expressions within string literals:

string name = "Alice"; 
int age = 30; 
string message = $"My name is {name} and I'm {age} years old."; // String interpolation

Comparing Strings

We can compare strings using equality (==), inequality (!=), or string comparison methods like Equals().

string str1 = "hello"; 
string str2 = "HELLO"; 
bool areEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase); // Case-insensitive comparisonx