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.
0
0
String searching and extraction in C Sharp (C#)
Introduction
Finding a word in a sentence to check if it exists.
Getting a person's name from a full address string.
Extracting a date from a message.
Checking if a password contains a special character.
Cutting out a part of a text to show as a preview.
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
Finds the position of "world" in the text. Result is 6.
C Sharp (C#)
string text = "Hello world!"; int pos = text.IndexOf("world");
Extracts 5 characters starting at position 6, which is "world".
C Sharp (C#)
string text = "Hello world!"; string part = text.Substring(6, 5);
Searches for "moon" which is not in the text, so result is -1.
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."); } } }
OutputSuccess
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.