Strings in C#
# CHAPTER 10
Strings in C#
1. Introduction
Text manipulation is central to almost every application. Whether validating a password, searching a database, or formatting a report, you will work extensively withstring. In C#, strings are powerful, but they have a unique memory behavior that every developer must understand to avoid performance bottlenecks.
2. Learning Objectives
By the end of this chapter, you will be able to:- Use built-in String methods for text manipulation.
- Understand Escape Characters.
- Explain the concept of String Immutability.
-
Use
StringBuilderfor high-performance string manipulation.
3. Built-in String Methods
Thestring class contains dozens of methods to manipulate text easily.
4. Escape Characters
If you want to print a double-quote inside a string, it confuses the compiler because double-quotes are used to define the string itself. You must "escape" special characters using a backslash\.
| Character | Meaning | Example |
|---|---|---|
\" | Double Quote | "He said \"Hello\"." |
\n | New Line | "Line 1\nLine 2" |
\t | Tab | "Column1\tColumn2" |
\\ | Backslash | "C:\\Folder\\File.txt" |
Verbatim Strings (@):
Instead of using \\ for file paths, prefix the string with @ to ignore all escape characters.
5. OOP and Memory: String Immutability (CRITICAL)
In C#, strings are immutable. Once a string is created in the Heap memory, it can NEVER be changed.When you add " Doe" to "John", C# does NOT modify "John". Instead, it:
- 1. Creates a brand new block of memory for "John Doe".
-
2.
Changes the
namevariable to point to the new memory.
- 3. Leaves the original "John" string in memory until the Garbage Collector deletes it.
If you concatenate strings in a for loop 10,000 times, you will create 10,000 abandoned strings in memory, causing massive lag!
6. The Solution: StringBuilder
When performing heavy string manipulation (like inside loops), use the StringBuilder class. It manages a dynamic buffer and modifies text *in-place* without creating abandoned strings.
*(Requires using System.Text;)*
7. Common Mistakes
-
Using
==vs.Equals(): In Java, you must use.Equals()to compare strings. In C#, the==operator is heavily overloaded to compare the actual *value* of the strings safely.if(name == "Admin")is perfectly valid and preferred in C#.
-
Ignoring Case Sensitivity:
"apple" == "Apple"isfalse. Always use.ToLower()before comparing user input.
8. Best Practices
-
Use standard strings and the
+operator (or interpolation$"") for simple concatenation (1-5 operations).
-
Always use
StringBuilderif you are modifying a string inside a loop.
9. Exercises
-
1.
Write a program that asks for a user's full name, and prints their initials using
Substring().
-
2.
Given the string
"C:\Users\Admin\Desktop", print it to the console using a verbatim string literal (@).
10. MCQs with Answers
What property returns the number of characters in a string?
Which method removes spaces from the beginning and end of a string?
What does it mean that strings are "Immutable"?
Which character acts as the escape character in C# strings?
How do you print a newline inside a standard string?
What does placing an @ symbol before a string do?
What class should you use to concatenate strings inside a large loop?
Which namespace is required to use StringBuilder?
"HELLO" == "hello" true or false in C#?
a) True b) False
Answer: b) False (C# strings are case-sensitive)
What does text.Substring(0, 3) return if text is "Batman"?
11. Interview Questions
- Q: Explain String Immutability and why it exists.
-
Q: Describe the exact scenario where you would choose
StringBuilderover standard string concatenation.
-
Q: What happens in memory when you execute
string s = "A"; s += "B"; s += "C";?
12. Summary
Strings are feature-rich but immutable. Methods like.Trim() and .ToUpper() return brand new strings rather than modifying the original. For heavy text assembly, utilizing StringBuilder is a critical optimization technique to prevent memory bloat and Garbage Collector lag.
13. Next Chapter Recommendation
Up until now, all our code has been trapped inside theMain method. In Chapter 11: Methods and Parameters, we will learn how to break our code into reusable, organized blocks.