C# String Operations and Formatting Explained

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:

MethodDescriptionExample
LengthReturns number of charactersname.Length
ToUpper()Converts to uppercasename.ToUpper()
ToLower()Converts to lowercasename.ToLower()
Contains("x")Checks if substring existsname.Contains("am")
StartsWith("J")Checks if string starts with somethingname.StartsWith("J")
EndsWith("s")Checks if string ends with somethingname.EndsWith("s")
Replace("a", "@")Replaces part of the stringname.Replace("a", "@")
Trim()Removes spaces from both ends" hello ".Trim()
Substring(start, len)Extracts part of a stringname.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.OrdinalIgnoreCase when 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

ConceptSyntax Example
Concatenation"Hello " + name
Interpolation$"Hi {name}"
Methodsname.ToUpper(), name.Length
Comparisona == b, a.Equals(b, OrdinalIgnoreCase)
Formattingstring.Format("Hello {0}", name)
Splitting/JoiningSplit(','), `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.