CodeBlanks Logo Icon CodeBlanks

IndexOf and LastIndexOf

C# course · Beginner · Lesson 89/116

Learn to search with IndexOf and LastIndexOf.

Searching with IndexOf

The IndexOf method returns the first position of a substring inside a string. If it cannot find it, it returns -1. That return value lets you guard the search with an if.

For example, "alex@codeblanks".IndexOf('@') returns 4 because the '@' sign sits at the fourth index. The search is case-sensitive, so IndexOf('A') and IndexOf('a') may give different results.

Last position with LastIndexOf

The LastIndexOf method returns the last position of a substring inside a string. It is ideal for finding the final folder name in a file path or the last '/' in a URL. If not found, it also returns -1.

Example: "a/b/c.txt".LastIndexOf('/') returns 3. Then Substring(lastSlash + 1) yields just the file name. This is a common pattern in file-handling code.

Providing a start index

IndexOf and LastIndexOf accept a second argument as a starting position. IndexOf('a', 5) begins the search at index 5 and skips earlier matches. This is useful for walking through multiple occurrences in a string.

For example, to visit every space in a text you start each search one past the previous hit. The loop then advances through the string and ends when the call returns -1.

Exercise Find the file name

Get the position of the last '/' in path using LastIndexOf and store it in lastSlash. Then call Substring(lastSlash + 1) to assign the file name to fileName and print it with Console.WriteLine.

Show example solution
Get lastSlash = path.LastIndexOf('/'); then fileName = path.Substring(lastSlash + 1); and print it.
Example solution:
using System;

class Program
{
    static void Main()
    {
        string path = "docs/reports/2024.pdf";
        int lastSlash = path.LastIndexOf('/');
        string fileName = path.Substring(lastSlash + 1);
        Console.WriteLine(fileName);
    }
}

Test yourself

  1. What does IndexOf return when the substring is missing?

    int i = "hello".IndexOf('z');
    • 0
    • -1
    • null
    • Throws FormatException
    Show answer

    -1 — Correct! IndexOf returns -1 when nothing is found; it cannot return null.

  2. Position of the last slash

    string path = "a/b/c.txt";
    int lastSlash = path____;
    Console.WriteLine(lastSlash);
    Show answer
    string path = "a/b/c.txt";
    int lastSlash = path.LastIndexOf('/');
    Console.WriteLine(lastSlash);
  3. Match the call with its result

    "hello".IndexOf('l')
    2
    "hello".LastIndexOf('l')
    3
    "hello".IndexOf('z')
    -1

All lessons in Beginner