Skip to main content

19. Strings in C#

Level: Beginner
Goal: Learn how to store, clean, check, join, and display text in C#.

ℹ️ What You'll Learn
  • What a string is
  • Clean text using Trim
  • Change text using ToUpper and ToLower
  • Check text using Contains, StartsWith, and EndsWith
  • Split text into parts
  • Build output using string interpolation
  • Use StringBuilder for many lines

A string is text.

In a school application, these are strings:

  • Student name: "Sahasra Kumar"
  • Roll number: "STU-001"
  • Class name: "10th"
  • Email: "Sahasra@example.com"
  • Fee status: "Paid"

Why Strings Matter

Most user input comes as text first.

Examples:

  • A student enters their name in a form.
  • A teacher enters exam remarks.
  • An admin searches by roll number.
  • A report card prints student details.

So before writing big programs, you must become comfortable with strings.

Quick Definitions

  • String - Text data type (e.g., "Sahasra Kumar")
  • Immutable - Cannot be changed after creation (creates new string when modified)
  • Trim - Remove extra spaces at start and end
  • Interpolation - Placing variables inside text using $"text {variable}"
  • StringBuilder - Efficient class for building many text lines
  • Split - Break text into parts using a separator
  • Substring - Extract part of a string
  • Contains - Check if text exists inside another text
  • StartsWith/EndsWith - Check beginning or ending of string
  • IsNullOrWhiteSpace - Check for empty, null, or only spaces

Create a String

string studentName = "Sahasra Kumar";
string className = "10th";
string rollNumber = "STU-001";

Console.WriteLine(studentName);
Console.WriteLine(className);
Console.WriteLine(rollNumber);

String Length

Length tells how many characters are inside the string.

string name = "Sahasra";

Console.WriteLine(name.Length); // 4

This is useful when validating input.

string password = "abc";

if (password.Length < 6)
{
Console.WriteLine("Password is too short");
}

Common String Methods

MethodMeaningExample
Trim()Removes extra spaces at start and end" Sahasra ".Trim()
ToUpper()Converts text to uppercase"Sahasra".ToUpper()
ToLower()Converts text to lowercase"Sahasra".ToLower()
Contains()Checks if text exists inside"Sahasra Kumar".Contains("Kumar")
StartsWith()Checks starting text"STU-001".StartsWith("STU")
EndsWith()Checks ending text"photo.jpg".EndsWith(".jpg")
Replace()Replaces text"10-A".Replace("-", "/")
Split()Breaks text into parts"Sahasra,10th,A".Split(',')

Clean User Input

Students may type extra spaces by mistake.

string input = " Sahasra Kumar ";

string cleanedName = input.Trim();

Console.WriteLine(cleanedName); // Sahasra Kumar

Important point: Trim() does not change the original string. It returns a new string.

string input = " Sahasra ";

input.Trim();

Console.WriteLine(input); // still has spaces

Correct:

string input = " Sahasra ";

input = input.Trim();

Console.WriteLine(input); // Sahasra

Check Empty Text

Use string.IsNullOrWhiteSpace() for required fields.

string name = " ";

if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Name is required");
}

This handles:

  • null
  • empty text ""
  • only spaces " "

Join Text with Interpolation

String interpolation means placing variables inside text using $.

string name = "Sahasra";
string className = "10th";

Console.WriteLine($"Student {name} is studying in class {className}");

Output:

Student Sahasra is studying in class 10th

This is easier to read than using + many times.

Format Numbers Inside Strings

double percentage = 87.4567;
decimal fee = 25000;

Console.WriteLine($"Percentage: {percentage:F2}");
Console.WriteLine($"Fee: {fee:C}");

F2 means show 2 digits after decimal.

Split Text

Sometimes data comes as one line.

string line = "STU-001,Sahasra Kumar,10th,A";

string[] parts = line.Split(',');

Console.WriteLine(parts[0]); // STU-001
Console.WriteLine(parts[1]); // Sahasra Kumar
Console.WriteLine(parts[2]); // 10th
Console.WriteLine(parts[3]); // A

This is common when reading CSV files.

Strings Are Immutable

Immutable means once a string is created, it cannot be changed.

When you modify a string, C# creates a new string.

string name = "Sahasra";

string upperName = name.ToUpper();

Console.WriteLine(name); // Sahasra
Console.WriteLine(upperName); // Sahasra

This is safe, but repeated changes in loops can become slow.

Use StringBuilder for Many Lines

If you are building a report with many lines, use StringBuilder.

var report = new System.Text.StringBuilder();

report.AppendLine("School Report");
report.AppendLine("-------------");
report.AppendLine("Name: Sahasra Kumar");
report.AppendLine("Class: 10th");
report.AppendLine("Result: Pass");

Console.WriteLine(report.ToString());

School Management Example

Create a simple student summary.

💻 Try It — Console App
💡 Paste into Program.cs and run⌥ GitHub
string rollNumber = " STU-001 ";
string name = " Sahasra kumar ";
string className = "10th";
double percentage = 87.456;

rollNumber = rollNumber.Trim().ToUpper();
name = name.Trim();

string message = $"Roll: {rollNumber}\nName: {name}\nClass: {className}\nPercentage: {percentage:F2}%";

Console.WriteLine(message);

When You'll Use This in SMS

Every SMS feature uses strings.

Real string operations:

Student name validation: Trim(), Length check
Roll number format: StartsWith("STU-"), split by "-"
Email validation: Contains("@"), EndsWith(".com")
Password validation: Length >= 8
Report generation: Interpolation to build formatted text
CSV import: Split(',') to parse student data
Log messages: Interpolation for user-friendly errors

Real SMS code:

string name = studentInput.Trim();
if (name.Length < 2) throw new ArgumentException("Name too short");

string email = input.ToLower();
if (!email.Contains("@")) throw new ArgumentException("Invalid email");

string csvLine = $"{student.RollNumber},{student.Name},{student.Email}";

StringBuilder report = new StringBuilder();
report.AppendLine("=== Report ===");
report.AppendLine($"Generated: {DateTime.Now}");

Real impact: SMS processes 1000+ strings per session. Performance depends on string handling.


Try This Now

Run the student summary example above. Then experiment:

  1. Add email field and validate Contains("@")
  2. Validate roll number starts with "STU-"
  3. Add more fields and use StringBuilder instead of string +
  4. Read from CSV: split line by comma
  5. Count students where name starts with "S"

See how string methods organize and validate student data.


ℹ️ Video Tutorial

Strings explained: Trim, ToUpper, ToLower, Contains, Split, Interpolation, StringBuilder, immutability. Video coming soon. Subscribe to NexCoding YouTube for updates.


Common Mistakes

Mistake 1: Forgetting to assign the result.

string name = " Sahasra ";
name.Trim(); // wrong

Correct:

name = name.Trim();

Mistake 2: Checking only empty text.

if (name == "")
{
Console.WriteLine("Invalid");
}

Better:

if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Invalid");
}

Mistake 3: Using + too much for reports.

string report = "";
report = report + "Line 1\n";
report = report + "Line 2\n";

Better:

var report = new System.Text.StringBuilder();
report.AppendLine("Line 1");
report.AppendLine("Line 2");

Best Practices

  • Use Trim() before validating user input.
  • Use IsNullOrWhiteSpace() for required text.
  • Use string interpolation for readable output.
  • Use StringBuilder for long reports or loops.
  • Use ToUpper() or ToLower() when comparing text safely.
  • Remember that string methods return a new string.

Practice Task

Create a program that asks for:

  • Student name
  • Roll number
  • Class name

Then:

  • Remove extra spaces
  • Convert roll number to uppercase
  • Print a clean student profile

Quick Revision

  • string stores text.
  • Trim() removes extra spaces.
  • Contains() checks whether text exists inside another text.
  • Split() breaks text into parts.
  • Strings are immutable.
  • StringBuilder is useful for reports and repeated text building.
🎯 Q1: What is a string in C#?

A string is a data type used to store text, like student name, email, roll number, or address.

🎯 Q2: Why should we use Trim()?

Trim() removes extra spaces from the beginning and end of user input. This helps validation work correctly.

🎯 Q3: What does immutable string mean?

It means the original string cannot be changed. Any string method returns a new string.

🎯 Q4: When should we use StringBuilder?

Use StringBuilder when creating long text, reports, or adding text repeatedly inside a loop.

🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on C# strings. Try these prompts:

  • "Explain C# strings with student examples"
  • "Give me 10 beginner exercises for C# string methods"
  • "Explain StringBuilder in simple words"
  • "How do I validate student name input in C#?"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

Tuples in C# ->

nexcoding.in