String searching and extraction in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we search or extract parts of a string, the time it takes depends on the string's length.
We want to know how the work grows as the string gets longer.
Analyze the time complexity of the following code snippet.
string text = "Hello, welcome to the world of C# programming.";
string wordToFind = "world";
int index = text.IndexOf(wordToFind);
if (index != -1)
{
string extracted = text.Substring(index, wordToFind.Length);
Console.WriteLine(extracted);
}
This code searches for a word inside a string and extracts it if found.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The search method
IndexOfscans the string to find the word. - How many times: It checks characters one by one until it finds the word or reaches the end.
As the string gets longer, the search checks more characters.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The work grows roughly in direct proportion to the string length.
Time Complexity: O(n * m)
This means the time to search grows linearly with the string length and the word length.
[X] Wrong: "Searching a string is always instant, no matter how long it is."
[OK] Correct: The program must check characters one by one, so longer strings take more time.
Understanding how string search time grows helps you explain efficiency clearly and shows you know how programs handle text.
"What if we searched for multiple words one after another? How would the time complexity change?"
Practice
IndexOf method return if the searched substring is not found in a string?Solution
Step 1: Understand
TheIndexOfbehaviorIndexOfmethod returns the zero-based index of the first occurrence of the substring if found.Step 2: Check return value when substring is missing
If the substring is not found,IndexOfreturns -1 to indicate absence.Final Answer:
-1 -> Option BQuick Check:
IndexOfreturns -1 if substring missing [OK]
- Thinking it returns 0 when not found
- Expecting null instead of -1
- Assuming it throws an error if missing
text?Solution
Step 1: Recall
Substringmethod signatureSubstringtakes start index first, then length:Substring(int startIndex, int length).Step 2: Match correct syntax
text.Substring(3, 5); uses correct method name and parameter order: start at 3, length 5.Final Answer:
text.Substring(3, 5); -> Option AQuick Check:
Correct method and parameters = text.Substring(3, 5); [OK]
- Using wrong method name like Substr or SubString
- Swapping start index and length parameters
- Using only one parameter when two are needed
string s = "hello world";
int pos = s.IndexOf("world");
string part = s.Substring(pos, 5);
Console.WriteLine(part);Solution
Step 1: Find index of "world" in string
"world" starts at index 6 in "hello world".Step 2: Extract substring from index 6 with length 5
Substring(6, 5) extracts "world" exactly.Final Answer:
world -> Option CQuick Check:
IndexOf + Substring extracts "world" [OK]
- Using wrong start index for Substring
- Confusing length parameter
- Expecting output to include extra characters
string s = "example";
int pos = s.IndexOf("z");
string part = s.Substring(pos, 3);
Console.WriteLine(part);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 AQuick Check:
Negative index in Substring causes error [OK]
- Assuming IndexOf throws exception when not found
- Ignoring negative index causes Substring error
- Blaming Console.WriteLine for error
string sentence. Which code correctly extracts the first word assuming words are separated by spaces?Solution
Step 1: Find position of first space
UseIndexOf(' ')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 DQuick Check:
Check for space, then substring from start [OK]
- Not handling case when no space exists
- Extracting substring after space instead of before
- Using wrong substring parameters
