C# · Data

Strings

Names, emails, messages, file paths — most data you handle is text. C# strings come with a toolbox of methods for cleaning, searching and building text.

Beginner 5 min Lesson 9 of 26Examples target C# 13 on .NET 9 unless stated otherwise.
Before you start:Variables and Data Types
0/26 in C#
On this page · 5 min · Beginner

In simple words#

A string is a necklace of characters. You can read beads, copy them or make a new necklace — but you never change the original one (strings are immutable).

String
Text, a sequence of characters.
Interpolation
quot;Hello {name}" puts values inside text.
Immutable
Every “change” creates a new string.

Learning objectives#

  • Build strings with interpolation and formatting
  • Clean and search text with Trim, Contains, StartsWith and Replace
  • Split text into parts and join parts back
  • Know that strings are immutable and when to use StringBuilder

Explanation#

Strings are immutable: methods like ToUpper or Replace never change the original — they return a new string. Always use the returned value.

Trim removes spaces at both ends. Contains, StartsWith and EndsWith search. Replace swaps text. Substring(start, length) cuts out a piece.

Comparing user input? Ignore case with StringComparison.OrdinalIgnoreCase, for example email.Equals(other, StringComparison.OrdinalIgnoreCase).

Split(',') breaks text into an array; string.Join(", ", items) does the reverse. string.IsNullOrWhiteSpace checks for empty input.

Verbatim strings start with @ and treat backslashes literally — handy for Windows paths. Raw string literals (""" ... """) are great for JSON and multi-line text.

Building a string in a loop with += creates a new string every time. StringBuilder (in System.Text) appends efficiently.

Syntax#

C# Illustrative
string s = 
quot;Hi
{name}, total {total:F2}";
string clean = input.Trim().ToLower(); string[] parts = csv.Split(','); string path = @"C:\data\files";

Code example: Cleaning up user input#

C#Program.cs Illustrative
using System.Text;


string name = "  Asha Rao  ";
string clean = name.Trim();
Console.WriteLine(
quot;[
{clean}] has {clean.Length} characters");
Console.WriteLine(clean.ToUpper()); Console.WriteLine(clean.Contains("Rao")); Console.WriteLine(clean.StartsWith("asha", StringComparison.OrdinalIgnoreCase)); Console.WriteLine(clean.Replace("Rao", "Iyer")); Console.WriteLine(clean.Substring(0, 4)); string[] colours = "red,green,blue".Split(','); Console.WriteLine(colours[1]); Console.WriteLine(string.Join(" | ", colours)); Console.WriteLine(string.IsNullOrWhiteSpace(" ")); string path = @"C:\reports\2026"; Console.WriteLine(path); var sb = new StringBuilder(); for (int i = 1; i <= 3; i++) { sb.Append(i).Append(';'); } Console.WriteLine(sb.ToString());
Expected output
[Asha Rao] has 8 characters
ASHA RAO
True
True
Asha Iyer
Asha
green
red | green | blue
True
C:\reports\2026
1;2;3;

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. Trim returns a new string without the outer spaces; name itself is unchanged.
  2. ToUpper, Contains and Replace each return new values.
  3. StartsWith with OrdinalIgnoreCase matches "asha" against "Asha".
  4. Substring(0, 4) takes 4 characters starting at index 0.
  5. Split makes an array; Join glues it back with a different separator.
  6. The @ verbatim string keeps the backslashes as they are.
  7. StringBuilder collects pieces and produces one string at the end.

Real-world use case#

A sign-up API trims and lower-cases emails before saving, compares them case-insensitively to prevent duplicate accounts, and builds a CSV export of users with StringBuilder.

Common mistakes#

Ignoring the return value

name.Trim(); on its own does nothing useful. Write name = name.Trim();.

Comparing with ToLower() everywhere

a.ToLower() == b.ToLower() allocates two new strings. a.Equals(b, StringComparison.OrdinalIgnoreCase) is clearer and faster.

Substring past the end

Substring(0, 20) on an 8-character string throws ArgumentOutOfRangeException. Check Length first.

Best practices#

  • Prefer interpolation over + concatenation
  • Use StringComparison explicitly when comparing user text
  • Use StringBuilder for strings built in loops
  • Validate with string.IsNullOrWhiteSpace

Remember this#

Strings never change — methods return NEW strings.

Split = text → array. Join = array → text.

@"C:\path" = backslashes stay as they are.

Practice exercise#

Your task: Given string fullName = " ravi KUMAR ", print it as "Ravi Kumar" (trimmed, each word capitalised).

Need a hint?
Trim, Split on a space, then for each word: first letter upper + rest lower. Join with a space.
Show solution
C# Illustrative
string fullName = "  ravi KUMAR ";
string[] words = fullName.Trim().Split(' ');
for (int i = 0; i < words.Length; i++)
{
    words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower();
}
Console.WriteLine(string.Join(" ", words));   // Ravi Kumar

Mini quiz#

Strings quizPredict the output Question 1 of 3

What is printed?

string s = "hello";
s.ToUpper();
Console.WriteLine(s);
Score so far: 0/0

Want more? Practise all C# MCQs · C# interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.