How to Find Substring in C#: Simple Methods Explained
In C#, you can find a substring using the
IndexOf method, which returns the position of the substring or -1 if not found. Alternatively, use Contains to check if the substring exists, returning a boolean value.Syntax
The main methods to find a substring in C# are:
int IndexOf(string value): Returns the zero-based index of the first occurrence ofvalueor -1 if not found.bool Contains(string value): Returnstrueifvalueexists in the string, otherwisefalse.
csharp
string text = "Hello, world!"; int position = text.IndexOf("world"); bool exists = text.Contains("Hello");
Example
This example shows how to find the position of a substring and check if it exists in a string.
csharp
using System; class Program { static void Main() { string text = "Hello, world!"; int index = text.IndexOf("world"); if (index != -1) { Console.WriteLine($"Substring 'world' found at position: {index}"); } else { Console.WriteLine("Substring not found."); } bool containsHello = text.Contains("Hello"); Console.WriteLine($"Does the text contain 'Hello'? {containsHello}"); } }
Output
Substring 'world' found at position: 7
Does the text contain 'Hello'? True
Common Pitfalls
Common mistakes when finding substrings include:
- Not checking if
IndexOfreturns -1 before using the index. - Ignoring case sensitivity;
IndexOfandContainsare case-sensitive by default. - Using
Containswhen you need the position of the substring.
To perform case-insensitive search, use IndexOf with StringComparison.OrdinalIgnoreCase.
csharp
string text = "Hello, World!"; // Wrong: assumes substring always found int pos = text.IndexOf("world"); Console.WriteLine(pos + 1); // Will print 0 because pos is -1 // Right: check if found int pos2 = text.IndexOf("world", StringComparison.OrdinalIgnoreCase); if (pos2 != -1) { Console.WriteLine($"Found at position {pos2}"); } else { Console.WriteLine("Not found"); }
Output
0
Found at position 7
Quick Reference
| Method | Description | Return Type | Case Sensitivity |
|---|---|---|---|
| IndexOf(string value) | Finds position of substring or -1 if not found | int | Case-sensitive by default |
| IndexOf(string value, StringComparison) | Finds position with case options | int | Depends on StringComparison |
| Contains(string value) | Checks if substring exists | bool | Case-sensitive by default |
Key Takeaways
Use IndexOf to get the position of a substring; it returns -1 if not found.
Use Contains to check if a substring exists, returning true or false.
Always check for -1 from IndexOf before using the index to avoid errors.
For case-insensitive search, use IndexOf with StringComparison.OrdinalIgnoreCase.
Contains does not provide position, only existence.