6️⃣ C# Arrays & Strings
Estimated reading: 3 minutes 282 views

C# Strings – Complete Guide to Text Handling in C#


Introduction – Why Learn Strings in C#?

Strings are a cornerstone of application development. Whether you’re building a web form, processing file paths, or constructing JSON responsesβ€”strings play a pivotal role. In C#, strings are powerful, object-oriented, and immutable, offering numerous methods for manipulation, validation, and formatting.

In this guide, you’ll learn:

  • What strings are and how they work in C#
  • String declaration, formatting, and interpolation
  • Common string methods and operations
  • Immutable behavior and StringBuilder use
  • Real-world examples and best practices

Core Concept – What Is a String in C#?

A string in C# is a sequence of Unicode characters represented by the System.String class. Strings are immutable, meaning any change results in a new string object.

Syntax:

string welcome = "Hello, World!";

Code Example – Basic String Operations

string firstName = "Alice";
string greeting = "Hello, " + firstName + "!";
Console.WriteLine(greeting);

Output:

Hello, Alice!

Explanation:

  • Strings are concatenated using +.
  • Immutable nature means a new string is returned after modification.

String Methods – Useful and Common Operations

string title = "  Learn C# Strings  ";

Console.WriteLine(title.Trim());             // Removes extra spaces
Console.WriteLine(title.ToUpper());          // Converts to uppercase
Console.WriteLine(title.Contains("C#"));     // Checks for substring
Console.WriteLine(title.Replace("C#", "CSharp")); // Replaces substring

Other Common Methods:

  • .Length
  • .ToLower()
  • .Substring(start, length)
  • .Split(delimiter)
  • .StartsWith(), .EndsWith()
  • .IndexOf()

String Interpolation – Clean, Readable Formatting

string name = "Bob";
int age = 30;

Console.WriteLine($"Name: {name}, Age: {age}");

Use Case: Simplifies formatting over + concatenation.


String Immutability & StringBuilder

Since strings are immutable, repeated modifications inside loops can lead to memory overhead. Use StringBuilder to optimize:

StringBuilder sb = new StringBuilder();
sb.Append("Welcome ");
sb.Append("to ");
sb.Append("C#");
Console.WriteLine(sb.ToString());

Use Case: Efficient when concatenating strings dynamically.


Escape Sequences

Escape CodeDescriptionExample Result
\nNew lineLine 1 ↡ Line 2
\tTab spaceIndented text
\"Double quote"text"
\\BackslashC:\\Files\\Path

Verbatim Strings – Ignore Escapes Using @

string path = @"C:\Program Files\App";

Use Case: Clean file paths and multi-line strings.


String Comparison – Equals and Compare

string a = "Test";
string b = "test";

Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // true

Use StringComparison.OrdinalIgnoreCase for case-insensitive checks.


Real-World Use Cases

  • πŸ“© Formatting email templates
  • Building URLs and API queries
  • Validating passwords or inputs
  • Generating reports, file content
  • Processing CSV, JSON, or XML data

Summary – Recap & Next Steps

Key Takeaways:

  • Strings are immutable and offer a rich API.
  • Use interpolation for cleaner code, and StringBuilder for large dynamic operations.
  • Methods like .Trim(), .Replace(), .Split() make manipulation easy.

Real-world relevance: Strings are central to data exchange, UI rendering, logging, and file handling in any .NET app.


FAQ Section

Are strings mutable in C#?
No, strings are immutable. Use StringBuilder for performance when changing values repeatedly.


What’s the difference between == and .Equals()?
Both compare values. .Equals() can be used with StringComparison for case sensitivity control.


How do I check for an empty or null string?
Use string.IsNullOrEmpty() or string.IsNullOrWhiteSpace().


Can I format numbers and dates in strings?
Yes. Use interpolated strings or string.Format():

string price = $"{123.45:C}";

How do I split a sentence into words?
Use .Split():

string[] words = sentence.Split(' ');

Share Now :
Share

πŸ“š C# Strings

Or Copy Link

CONTENTS
Scroll to Top