C# IndexOf : How to locate a string or substring

c# indexofC# is an object oriented programming language introduced by Microsoft in the year 2000. The language is made to work with the .NET framework. C# lets you build reusable chunks of code that can be used to make different types of .NET based applications, like database software, XML web service apps, Windows client apps, client-server apps and distributables. The language is based to a large extent on C and C++, but it borrows heavily from other languages as well, like Java and Delphi. If you’ve ever studied any of these languages before, you’ll notice how similar C# code is to theirs. C# sharp, like Java, is a portable language. You can write the code for an application once and run it anywhere, regardless of the architecture of the machine – provided you have the .NET framework installed on that machine. If you’re new to C#, you can take this 1 hour crash course for C#.

The .NET Common Language Runtime (CLR) is essential to the running of a C# based application because it performs several essential programming tasks (that you don’t have to write the code for), like handling exceptions, assigning and freeing up memory and performing garbage collection. The CLR also acts as an intermediary between C# and the machine. The C# compiler does not produce machine language, like some other languages, but instead creates Intermediate Language (IL) code. The IL code is picked up by CLR and then it compiles it in real time (Just-In-Time) and then executes it, all the while managing system resources. Because of the CLR, the amount of code that you need to write to make a working application is minimal. This makes C# sharp an easy language to learn. If you’re looking to learn C#, you can sign up for our C# course. We cover all the important aspects of the language, from the basics to the advanced stuff.

In this tutorial, we’re going to take a look at the IndexOf method in C#. We’re assuming that you’re a beginner and understand the syntax of a typical C# program. If you haven’t gotten that far yet, you can check out this beginners course on the language to help you get started.

The C# IndexOf Method

The IndexOf method in C# is used to search a program for a string or a part of a string (substring). The method reports the zero-based index of the first occurrence of the Unicode character you specify in the string. It can also report the zero-based index of an entire substring. If it can’t locate the character or substring you’ve specified, it will report a negative one (-1) value. This index isn’t visible to you, the user. So how do you know if the character or substring you specified is present in the program? You can use a conditional statement and the Console.Write command line to print out a message if the string is present in the program. We’ll show you how this is done in our sample programs later in the article.

There are 4 variations of the IndexOf Method: the IndexOf Method, the IndexOfAny Method, the LastIndexOf Method and the LastIndexOfAny Method. Here’s what they each stand for:

  • The IndexOf Method: It reports a zero-based index the first time it encounters the Unicode character you specified in the string in the program. It will report a -1 value if it doesn’t encounter the character.
  • The IndexOfAny Method: It reports a zero-based index the first time it encoutners the Unicode character you specified in an array of Unicode characters in the program. It will report a -1 value if it doesn’t encounter the character in the program.
  • The LastIndexOf Method: It reports the zero-based index of the Unicode character you specify the final time it encounters the character in the string. This means that if there are two character occurrences in the string, it will report the index of the character it encountered last. It will report a -1 value if it doesn’t encounter the character in the program.
  • TheLastIndexOfAny Method: It reports the zero-based index of one or more specified Unicode characters the final time they occur in the Unicode array in the program. It will report a -1 value if it doesn’t encounter the specified characters in the program.

These methods have several sub-variations that you need in different situations. By adding an int value to the parameters, for example, you can change the position where the methods begin their search for the character or substring you’ve specified. For a list of all the sub-variations, you can check out the official documentation. If you’re having trouble understanding any of the terminology we’ve used so far, consider signing up for our beginners C# course.

Examples of the C# IndexOf Method

We’ll write a few simple programs to help you understand the method. Let’s write a program to check whether a string “The world is round” contains the character “w”:

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

In this program, we created a string e containing the message “The world is round”. Then, we used the if conditional statement to check whether the character “w” was present in the string. Because the method IndexOf reports a -1 value if the character is absent in the string, we used the logical not equal (to !=) operator. Finally, we asked the program to print out “the specified string contains the character “w”” if the character was present in the program.

We can also write a program to check whether a given substring is present in a specified string. For example, we can check to see if the word “world” is present in the program above by changing it just a little:

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”");
}
Console.ReadLine();
}
}
Output: The specified string contains the substring “world”

We used the same logic in this program. We just replaced the character “w” with an entire substring “world”. Because the substring “world” was present in the program, it reported a 0 based index and we obtained the output “The specified string contains the substring “world””. If it wasn’t present in the program, we wouldn’t have obtained any output.

We can also have the program print out different parts of the string using the IndexOf method:

using System;
class Program
{
static void Main()
{
const string e = "The world is round, definitely";
int n = e.IndexOf('d');
string z = e.Substring(n);
Console.WriteLine(z);
Console.ReadLine();
}
}
Output: definitely

This program is a little more complex than the earlier ones. Do you see what we did in the program? First, we wrote a simple string e (notice the added word definitely, beginning with d). Then, we introduced a new int variable n that stores the zero based index value of the Unicode character d. Finally, we created a string z that can store the string value the index points towards (which is definitely). Then, we print the string!

You should try these programs yourself to if you want to understand the method better. For a more in-depth look into the method (including the sub-variations), consider signing up for this intermediate C# course. This course is comprehensive and covers the entire language, not just the IndexOf method. It should help you get a good understanding of how to write your own C# programs.