C# Strings

Working with text data in C#

📝 What are Strings?

Strings are sequences of characters used to store text in C#. They are enclosed in double quotes and can contain letters, numbers, symbols, and spaces.


// Creating a simple string
string greeting = "Hello, World!";
Console.WriteLine(greeting);
                                    

Output:

Hello, World!

String Basics

✍️

Creating Strings

Declare strings with double quotes

string name = "Alice";
string city = "New York";

Concatenation

Combine strings together

string first = "Hello";
string full = first + " World";
📏

String Length

Get the number of characters

string text = "Hello";
int length = text.Length; // 5
🔤

String Methods

Built-in functions for strings

string text = "hello";
text.ToUpper(); // "HELLO"

🔹 String Concatenation

String concatenation remains a foundational technique in C# for joining multiple string values into one cohesive output. Using the + operator, developers can combine literals, variables, and expressions, such as "Hello, " + userName + "!". While intuitive, excessive concatenation in loops can impact performance due to string immutability. For repeated operations, StringBuilder is more efficient. Understanding when to use concatenation versus interpolation or StringBuilder is key for writing optimized, maintainable code that produces clear, user-friendly text outputs in applications ranging from console programs to web interfaces.

// Using + operator
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);

// Using string interpolation (recommended)
string message = $"Hello, {firstName} {lastName}!";
Console.WriteLine(message);

Output:

John Doe

Hello, John Doe!

🔹 String Length

The Length property in C# returns the total number of characters in a string, providing a quick way to measure its size. Accessible as stringName.Length, it’s useful for validation—like checking for empty inputs—iterating through characters in loops, or truncating text. For example, if (input.Length == 0) Console.WriteLine("String is empty");. The property counts every character, including spaces and symbols, and helps in scenarios like bounding text fields, parsing data, and ensuring string operations stay within safe limits, improving both functionality and security.

string text = "Programming";
int length = text.Length;
Console.WriteLine($"The word '{text}' has {length} characters");

// Check if string is empty
string empty = "";
if (empty.Length == 0)
{
    Console.WriteLine("String is empty");
}

Output:

The word 'Programming' has 11 characters

String is empty

🔹 Common String Methods

C# includes a rich set of built-in string methods that simplify text manipulation without requiring custom logic. Key methods include ToUpper() and ToLower() for case conversion, Contains() for substring searches, Replace() for text substitution, and Substring() for extracting parts of a string. For example, "Hello".ToUpper() returns "HELLO". These methods enhance productivity, reduce code length, and improve readability. They are essential for data cleaning, user input processing, formatting outputs, and implementing search functionalities in applications across all domains.

🔸 ToUpper() and ToLower()

string text = "Hello World";
Console.WriteLine(text.ToUpper());  // Convert to uppercase
Console.WriteLine(text.ToLower());  // Convert to lowercase

Output:

HELLO WORLD

hello world

🔸 Contains() and Replace()

string sentence = "I love programming";

// Check if string contains a word
bool hasLove = sentence.Contains("love");
Console.WriteLine($"Contains 'love': {hasLove}");

// Replace text
string newSentence = sentence.Replace("love", "enjoy");
Console.WriteLine(newSentence);

Output:

Contains 'love': True

I enjoy programming

🔹 Accessing String Characters

Individual characters in a C# string can be accessed using zero-based index notation with square brackets, like text[0] for the first character. This allows direct inspection or manipulation of specific positions within the string. For example, char first = word[0]; stores the initial character. Remember that strings are immutable, so you cannot assign a new character directly via index; instead, convert to a char array. Character access is vital for parsing algorithms, encryption, validation checks, and custom string processing where positional analysis is required.

string word = "Hello";

// Access individual characters
char firstChar = word[0];    // 'H'
char lastChar = word[4];     // 'o'

Console.WriteLine($"First character: {firstChar}");
Console.WriteLine($"Last character: {lastChar}");

Output:

First character: H

Last character: o

🔹 String Interpolation

String interpolation in C# offers a streamlined syntax for embedding variables and expressions within strings by prefixing with $ and wrapping them in {}. It eliminates the clutter of concatenation operators and improves code clarity. For instance, $"The result is {value * 2}" directly incorporates calculations. Interpolation also supports formatting specifiers, such as {price:C2} for currency. This method is not only more readable but also reduces runtime errors from incorrect string assembly, making it a best practice for generating dynamic text in modern C# development.

string name = "Alice";
int age = 25;
double height = 5.6;

// String interpolation
string info = $"Name: {name}, Age: {age}, Height: {height}ft";
Console.WriteLine(info);

// With expressions
int x = 10, y = 20;
Console.WriteLine($"The sum of {x} and {y} is {x + y}");

Output:

Name: Alice, Age: 25, Height: 5.6ft

The sum of 10 and 20 is 30

🧠 Test Your Knowledge

Which symbol is used for string interpolation in C#?