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
StringBuilderuse - 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 Code | Description | Example Result |
|---|---|---|
\n | New line | Line 1 β΅ Line 2 |
\t | Tab space | Indented text |
\" | Double quote | "text" |
\\ | Backslash | C:\\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
StringBuilderfor 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 :
