Strings & Interpolation
Strings Are Everywhere
Almost every program deals with text β names, messages, passwords, URLs, emails. In C#, text lives inside string variables. A string is basically a chain of characters stored as a character array under the hood (that's literally why it's called a "string").
Here's the cool part: C# strings are immutable. That means once you create a string, you can't change it. Every time you "modify" a string, C# actually creates a brand new one behind the scenes. It's like writing in pen β you can't erase, you just write a new page.
String Basics & Interpolation
String Methods β Your Toolbox
Strings come packed with useful methods. Think of each method as a different tool:
.Lengthβ how many characters (it's a property, no parentheses).ToUpper()/.ToLower()β shout or whisper.Trim()β strips whitespace from both ends (great for user input).Contains("text")β does the string include this?.StartsWith()/.EndsWith()β check the beginning or end.Substring(start, length)β grab a piece of the string.Replace(old, new)β swap text.Split(separator)β break a string into an array.IndexOf("text")β find where something appears (-1 if not found)
Remember: these methods don't change the original string. They return a new string. You need to save the result!
String Methods in Action
StringBuilder β When Speed Matters
Remember how strings are immutable? That means every time you do result += "something" in a loop, C# creates a whole new string and throws the old one away. Do that 10,000 times and your program slows to a crawl.
StringBuilder is like a whiteboard β you can keep writing and erasing on the same board without making a new one each time. Use it when you're building up a big string piece by piece.
StringBuilder for Performance
Quick check
Continue reading