Look at this C# code that changes a string. What will it print?
string text = "Hello World"; string result = text.Replace("World", "C#"); Console.WriteLine(result);
Think about what the Replace method does to the string.
The Replace method swaps the word "World" with "C#" in the original string, so the output is "Hello C#".
This code trims spaces from a string. What will it print?
string input = " C# Programming ";
string trimmed = input.Trim();
Console.WriteLine(trimmed.Length);Count the characters after removing spaces at the start and end.
The original string has spaces at start and end. Trim() removes them, leaving "C# Programming" which has 14 characters.
Check these code snippets that access characters in a string. Which one will cause an error when run?
string s = "Code"; char c = s[4];
Remember string indexes start at 0 and go to length-1.
Index 4 is outside the string "Code" which has indexes 0 to 3, so accessing s[4] causes an IndexOutOfRangeException.
Strings in C# cannot be changed after creation. Why is this useful?
Think about safety and efficiency when many parts of a program use the same string.
Immutable strings can be shared safely without risk of changes, which improves performance and thread safety.
Analyze this C# code that formats a string with variables. What will it print?
int count = 3; string item = "apple"; string output = $"I have {count} {item}{(count > 1 ? "s" : "")}."; Console.WriteLine(output);
Look at how the conditional adds an 's' only if count is more than 1.
The code adds 's' to 'apple' because count is 3, so the output is "I have 3 apples."