Strings are one of the most commonly used data types in C#. Whether you’re building user interfaces, logging output, or processing data โ you’ll be working with text all the time. Understanding how to manipulate, format, and work with strings is essential for writing clean, efficient C# code.
Here we will cover the most useful string operations, including concatenation, interpolation, formatting, and built-in string methods. Youโll also learn best practices for comparing and handling strings effectively.
๐งต What is a String in C#?
A string is a sequence of characters, enclosed in double quotes:
string greeting = "Hello, world!";
Strings in C# are immutable, meaning once created, they canโt be changed โ but you can create modified copies using operations.
๐ String Concatenation
โ Using + Operator:
string firstName = "Alice";
string lastName = "Smith";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // Alice Smith
๐ก Concatenation creates a new string, not a modification of the original.
๐ง String Interpolation (Modern & Clean)
String interpolation is a clearer, preferred way to insert values into strings:
string name = "James";
int score = 95;
Console.WriteLine($"Player {name} scored {score} points.");
Just prefix the string with $ and use {} placeholders.
๐งฐ Common String Methods
Here are some of the most useful built-in methods:
| Method | Description | Example |
|---|---|---|
Length | Returns number of characters | name.Length |
ToUpper() | Converts to uppercase | name.ToUpper() |
ToLower() | Converts to lowercase | name.ToLower() |
Contains("x") | Checks if substring exists | name.Contains("am") |
StartsWith("J") | Checks if string starts with something | name.StartsWith("J") |
EndsWith("s") | Checks if string ends with something | name.EndsWith("s") |
Replace("a", "@") | Replaces part of the string | name.Replace("a", "@") |
Trim() | Removes spaces from both ends | " hello ".Trim() |
Substring(start, len) | Extracts part of a string | name.Substring(0, 3) |
๐ธ Example:
string product = " Keyboard ";
Console.WriteLine(product.Trim().ToUpper()); // KEYBOARD
๐ Comparing Strings
C# strings are case-sensitive by default:
string a = "hello";
string b = "Hello";
bool isEqual = a == b; // false
For case-insensitive comparison:
bool match = a.Equals(b, StringComparison.OrdinalIgnoreCase); // true
โ Use
StringComparison.OrdinalIgnoreCasewhen user input might vary in case.
๐ข String Formatting with string.Format()
A powerful method for templating:
string formatted = string.Format("Hello {0}, your balance is {1:C}", "Alex", 123.45);
// Output: Hello Alex, your balance is ยฃ123.45
Use
{0},{1}, etc. as placeholders. You can also format numbers and dates.
๐ฆ Splitting and Joining Strings
๐ธ Split:
string csv = "apple,banana,grape";
string[] fruits = csv.Split(',');
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
๐ธ Join:
string[] names = { "Alice", "Bob", "Charlie" };
string result = string.Join(" | ", names);
// Output: Alice | Bob | Charlie
๐ง StringBuilder (Advanced)
When building long or complex strings, use StringBuilder for better performance:
using System.Text;
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World!");
Console.WriteLine(sb.ToString());
โ Ideal for loops or large dynamic strings.
๐งช Practice Exercise
Write a method that:
- Accepts a userโs full name
- Returns it formatted as:
LASTNAME, Firstname - Handles extra spaces and capitalisation
static string FormatName(string fullName)
{
string trimmed = fullName.Trim();
string[] parts = trimmed.Split(' ');
if (parts.Length >= 2)
{
string first = char.ToUpper(parts[0][0]) + parts[0].Substring(1).ToLower();
string last = parts[1].ToUpper();
return $"{last}, {first}";
}
return fullName;
}
๐ Summary
| Concept | Syntax Example |
|---|---|
| Concatenation | "Hello " + name |
| Interpolation | $"Hi {name}" |
| Methods | name.ToUpper(), name.Length |
| Comparison | a == b, a.Equals(b, OrdinalIgnoreCase) |
| Formatting | string.Format("Hello {0}", name) |
| Splitting/Joining | Split(','), `Join(“ |
๐ฌ Want help with text manipulation or need a hand preparing for interviews and assessments? Contact us โ weโre always happy to help with code questions, project support, or personalised learning plans.