We use string searching and extraction to find specific words or parts inside a sentence or text. This helps us get useful information from bigger text.
String searching and extraction in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
string text = "your text here"; int index = text.IndexOf("searchTerm"); string part = text.Substring(startIndex, length);
IndexOf returns the position of the first match or -1 if not found.
Substring extracts part of the string starting at startIndex for length characters.
Examples
C Sharp (C#)
string text = "Hello world!"; int pos = text.IndexOf("world");
C Sharp (C#)
string text = "Hello world!"; string part = text.Substring(6, 5);
C Sharp (C#)
string text = "Hello world!"; int pos = text.IndexOf("moon");
Sample Program
This program looks for the word "fox" in the sentence. If found, it shows the position and extracts the word from the sentence.
C Sharp (C#)
using System; class Program { static void Main() { string sentence = "The quick brown fox jumps over the lazy dog."; string wordToFind = "fox"; int position = sentence.IndexOf(wordToFind); if (position != -1) { string extracted = sentence.Substring(position, wordToFind.Length); Console.WriteLine($"Found '{wordToFind}' at position {position}."); Console.WriteLine($"Extracted word: {extracted}"); } else { Console.WriteLine($"'{wordToFind}' not found in the sentence."); } } }
Important Notes
IndexOf is case-sensitive. Use ToLower() on both strings to search ignoring case.
Substring will throw an error if startIndex or length is out of range. Always check string length first.
Summary
Use IndexOf to find where a word or part starts in a string.
Use Substring to get a piece of the string by position and length.
Check if IndexOf returns -1 to know if the word is missing.
Practice
1. What does the
IndexOf method return if the searched substring is not found in a string?easy
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]
Hint: Remember: Not found means -1 from IndexOf [OK]
Common Mistakes:
- Thinking it returns 0 when not found
- Expecting null instead of -1
- Assuming it throws an error if missing
2. Which of the following is the correct syntax to extract a substring starting at index 3 with length 5 from a string
text?easy
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]
Hint: Remember: Substring(startIndex, length) with capital S [OK]
Common Mistakes:
- Using wrong method name like Substr or SubString
- Swapping start index and length parameters
- Using only one parameter when two are needed
3. What is the output of this code?
string s = "hello world";
int pos = s.IndexOf("world");
string part = s.Substring(pos, 5);
Console.WriteLine(part);medium
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]
Hint: IndexOf finds start, Substring extracts exact length [OK]
Common Mistakes:
- Using wrong start index for Substring
- Confusing length parameter
- Expecting output to include extra characters
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
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]
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
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]
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
- Using wrong substring parameters
