4. The following code throws an exception. What is the main cause?
string s = "example";
int pos = s.IndexOf("z");
string part = s.Substring(pos, 3);
Console.WriteLine(part);
medium
A. Substring called with negative start index
B. IndexOf throws exception if not found
C. Length parameter is too large
D. Console.WriteLine cannot print substrings
Solution
Step 1: Check IndexOf result for "z"
"z" is not in "example", so IndexOf returns -1.
Step 2: Substring called with start index -1 causes exception
Substring cannot start at negative index, so it throws ArgumentOutOfRangeException.
Final Answer:
Substring called with negative start index -> Option A
Quick Check:
Negative index in Substring causes error [OK]
Hint: Check if IndexOf is -1 before using Substring [OK]
Common Mistakes:
Assuming IndexOf throws exception when not found
Ignoring negative index causes Substring error
Blaming Console.WriteLine for error
5. You want to extract the first word from a sentence stored in string sentence. Which code correctly extracts the first word assuming words are separated by spaces?
hard
A. string firstWord = sentence.Substring(sentence.IndexOf(' ') + 1);
B. string firstWord = sentence.Substring(0, sentence.IndexOf(' '));
C. int spacePos = sentence.IndexOf(' ');
string firstWord = sentence.Substring(spacePos);
D. int spacePos = sentence.IndexOf(' ');
string firstWord = spacePos == -1 ? sentence : sentence.Substring(0, spacePos);
Solution
Step 1: Find position of first space
Use IndexOf(' ') to find where the first space is.
Step 2: Extract substring from start to space or whole string if no space
If no space found (-1), the whole sentence is one word; else extract from 0 to space position.
Final Answer:
int spacePos = sentence.IndexOf(' ');
string firstWord = spacePos == -1 ? sentence : sentence.Substring(0, spacePos); -> Option D
Quick Check:
Check for space, then substring from start [OK]
Hint: Check if space exists before substring to avoid errors [OK]
Common Mistakes:
Not handling case when no space exists
Extracting substring after space instead of before