0
0
CsharpHow-ToBeginner · 3 min read

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 of value or -1 if not found.
  • bool Contains(string value): Returns true if value exists in the string, otherwise false.
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 IndexOf returns -1 before using the index.
  • Ignoring case sensitivity; IndexOf and Contains are case-sensitive by default.
  • Using Contains when 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

MethodDescriptionReturn TypeCase Sensitivity
IndexOf(string value)Finds position of substring or -1 if not foundintCase-sensitive by default
IndexOf(string value, StringComparison)Finds position with case optionsintDepends on StringComparison
Contains(string value)Checks if substring existsboolCase-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.