This article addresses how to implement C# IndexOf into your coding toolset. Before you try these tutorials, we advise you to get familiar with the C# language. Syntax-wise, it has features that overlap with those of Java. That means once you’ve mastered Java, you’ll be brought up to speed on C#, too. Of course, there are still differences in how the two languages process reference calls, pointers, and broken code. 

Programming code on laptop screen

The versatile C# supports many internal frameworks

C# is widely recognized as an object-oriented language borrowed from its C/C++ predecessors. Microsoft released it to operate alongside the .NET framework. C# shares a few features with Java and Delphi in terms of its architecture. 

C# allows you to reuse blocks of code to develop the following:

Complete C# Masterclass

Last Updated January 2023

  • 287 lectures
  • All Levels
4.5 (23,879)

Learn C# Programming – WPF, Databases, Linq, Collections, Game Development with Unity. More than just the C# basics! | By Denis Panjuta, by Denis Panjuta

Explore Course

One advantage to coding in C# is the flexibility to run a program anywhere once it’s been finished, assuming you have .NET installed. The CLR performs tasks like freeing up space, handling exceptions, and collecting garbage. 

Fortunately, C# has less of a learning curve because you don’t have to write as much manual code, and every language has its own syntax for parsing characters from a string, or an array of items. 

How does IndexOf work in C#?

The IndexOf method detects the zero-based index of a string or character on its first occurrence. Otherwise, it will return a -1 to indicate that a character or string does not exist in the collection of string data. 

There are many variations of String.IndexOf() that take a parameter of the string item and a range of elements by index value. 

The syntax of an IndexOf char where x is the character to be searched:

//Str.IndexOf(char x)
public int IndexOf(char x)

//Str.IndexOf(charx, int start1)
Public int IndexOf(char x, int start1)

The char x parameter is always of the type System.Char compared to the Return Type, which is System.Int32. When the start and end range is specified, an exception will occur for out-of-range indexes. 

The purpose of C# IndexOf is to find a substring buried in a longer string or within an array of strings. It is used to determine if a string contains a certain letter, number, or entire word. 

An IndexOf is usually coupled with a While loop to examine multiple values one after another. Assign an if statement that has IndexOf to see the contents printed in the console whenever a word meets the right conditions. 

An overview of C# IndexOf for interpreting string types

The IndexOf method pinpoints the exact location of a Unicode character by getting its zero-based index. It helps retrieve substrings from the program as well. You only need to add a conditional statement and let the Console. Write command handle the output. 

There are four types of the method in total:

  1. IndexOf()
  2. IndexOfAny()
  3. LastIndexOf()
  4. LastIndexOfAny()

Although they are hard to distinguish, the “OfAny” will report on the first/last encounter of a Unicode character inside an array rather than a string. You can choose where to start the search by adding an integer to the parameter. 

Parsing unicode characters and substrings into IndexOf

Let’s think of a special program that can tell whether a string contains the character “H” and discover its respective index from the string “HelloGeeks”:

using System;
namespace ConsoleApplication2{
class Geeks {
    // Main Method
    static void Main(string[] args)
        string str = "HelloGeeks";  
        int index1 = str.IndexOf('H', 0);
        Console.WriteLine("The Index Value of character 'H' "+
                          "with start index 0 is " + index1);
        int index2 = str.IndexOf('H', 5);
        Console.WriteLine("The Index Value of character 'H' is " + index2);

This C# program illustrates the String.IndexOf(char x, int start1) method. It is apparent that we are looking for the 0 index, which corresponds to the letter “H.” However, the line: int index2 = str.IndexOf(‘H’, 5); returns the index -1 because there is no H with a position higher than the first one. 

You can also find occurrences of the string in the same manner. All you have to do is define a constant string set equal to a set of words. Input a substring into the IndexOf parameter to check for its presence. Write a message to the console verifying the substring is in the collection. 

Let’s write a simple program that checks for a given substring “world”:

using System;
class Example
static void Main()
const string e = "The world is round";
if (e.IndexOf("world") != -1)
Console.Write("The specified string contains the substring “world”");
Output: The specified string contains the substring “world”

The above code example produces an output of “world” because it employs the same logic as a character searcher, where the substring is passed into the IndexOf method for the static void main string, “The world is round”. In return, a zero-based index is reported, thus proving that “world” is present in the main string. 

How to extract rearranged pieces of a string

Similarly, C# IndexOf can retrieve any part of a string given the number of elements. Say you’re aiming to recover the greeting and closing statements. Consider this code snippet for extracting strings from a message: 

blablablablabllabl hello my friend. [email contents] Goodbye my friend blablablabla

The question is this: How do you get the start and end positions? Well, you would need to do a bit of math which produces the following output:

//Assign a variable to the message and pass an available IndexOf string to the method. Increment the length by 1 to get the start position. 

string email = "Bla bla hello my friend THIS IS THE STUFF I WANTGoodbye my friend"; 
int startPos = email.LastIndexOf("hello my friend") + "hello my friend".Length + 1; 

//The end index is reached by declaring an int length equal to the IndexOf for the closing sentence minus the beginning position. 

int length = email.IndexOf("Goodbye my friend") - startPos; 

//Write a .substring() that accepts the start index and the length integer as the parameters to read the substring. 

string sub = email.Substring(startPos, length);

//The finishing touch is to use Console writeline to print out the parsed string “sub”. 

Console.WriteLine("string before between is : {0}", sub);

When is it better to use IndexOfAny?

IndexOfAny() is a variant of the string mentioned above method. It searches for a character index belonging to the string and returns the first occurrence as an integer number. You could pass in more arguments to change the overloading capacity of the method. The format should look like this: string.IndexOfAny(char[ ]) where char[ ] is an array of characters that make up the string. 

The general syntax is declared as a public integer:

public int IndexOfAny(char[ ] ch)

Here is a program that exemplifies what IndexOfAny does. 

public static void Main()
        String str = "GeeksForGeeks";
        Console.WriteLine("Given String : {0}\n", str);
        char[] ch = { 's' };
        Console.WriteLine(str.IndexOfAny(ch) + 1);
        char[] ch1 = { 'a', 'b', 'c', 'e', 'f' };
        Console.WriteLine(str.IndexOfAny(ch1) + 1);
        char[] ch2 = { 'a', 'b', 'c' };
        int m = str.IndexOfAny(ch2);
        if (m > -1)
            Console.WriteLine("Not Found");

In the main method, define a string and write the 0 index to the console. To find a single character, you should start with the char array by setting it equivalent to any letter. This will run the search through the given string until it finds a matching character. Then, it discloses the position of your letter (e.g., “s” has an index of 5).

The char[ ] ch array is capable of matching many characters at once, in this case from “a” to “f.” Write the line using str.IndexOfAny() + 1 and pass in the ch parameter. Repeat this step for the ch1 and ch2 arrays. In the output, “e” should have an index of 2, and ch2 would return “Not Found” since those letters are not in the string. 

How do I get LastIndexOf in C#?

The LastIndexOf method identifies the index for the final occurrence of either a character or a string inside the invoked string object. It searches strings from right to left until it finds the last letter or substring, leaving out the for-loop.

In fact, C# LastIndexOf acts upon object instances of a string type. To reference them, you would need the string keyword or the string uppercase class. 

The resulting value is the index of the first character or string that matches the specified parameters. If the search returns empty, then it only has an index of -1. 

The general syntax of a LastIndexOf and other versions are displayed here:

Int var = LastIndexOf(char/string, index)

if (var != -1) { Console.WriteLine(string); }

This iterative method does a backward search, starting at a specific index position and moving towards the lowest index of the invoked string or a character. It always returns the last index of a char/string as long as the value is located in the whole string. 

Keep in mind that LastIndexOf() is case insensitive, meaning that the alphabetical order does not matter in a search. The length of the string is factored in as the number of characters that were counted. Above all, it must be wrapped in a public static void method, where the original string is also stored. 

If you need more practice, test out these programs for yourself and compare your answers to the solutions provided. However, to truly improve your coding skills, we suggest that you write a bunch of fun programs like the ones in this blog article. You can develop an ATM software, a movie database, or even an eCommerce app. 

It’s easy to get ahead on your programming journey. Start by creating an account to register for one of our courses on C#. At Udemy, we have many talented professionals teaching C# lessons, from navigating classes and interfaces to designing a 3D Unity game. 

Page Last Updated: December 2021

Top courses in C#

Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, Team, Gary Pettie
4.7 (37,774)
C#/.NET - 50 Essential Interview Questions (Junior Level)
Krystyna Ślusarczyk
4.9 (301)
Highest Rated
Design Patterns in C# Made Simple
Zoran Horvat
4.4 (304)
C#/.NET - 50 Essential Interview Questions (Mid Level)
Krystyna Ślusarczyk
4.8 (131)
C# Intermediate: Classes, Interfaces and OOP
Mosh Hamedani
4.5 (31,557)
Learn Parallel Programming with C# and .NET
Dmitri Nesteruk
4.5 (3,176)
Advanced Topics in C#
Dmitri Nesteruk
4.6 (354)
RPG Core Combat Creator: Learn Intermediate Unity C# Coding
Ben Tristem, Rick Davidson, Team
4.7 (10,397)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.5 (10,272)
Complete C# Masterclass
Denis Panjuta, by Denis Panjuta
4.5 (23,879)

More C# Courses

C# students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo