OneBite.Dev - Coding blog in a bite size

Find The Index Of A Substring Within A String In C#

Code snippet for how to Find The Index Of A Substring Within A String In C# with sample and detail explanation

Working with strings is a common task in many programming languages and C# is no exception. One of the everyday operations is finding the index of a substring in a larger string. This article illustrates how to do this in C#.

Code snippet: Finding the Index of a Substring in a String

string mainString = "Hello world, welcome to the world of C#";
string subString = "world";

int indexPosition = mainString.IndexOf(subString);

Console.WriteLine("Index: " + indexPosition);

Code Explanation: Finding the Index of a Substring in a String

The code starts by defining a string mainString which is the text in which we are going to search for a substring. The subString holds the value that we are searching for in the main text.

The IndexOf() function is a built-in C# function that accepts a string parameter and returns the starting index of the first occurrence of the string in the string from which the function is called. If the function doesn’t find the string, it returns -1.

In our example, mainString.IndexOf(subString) will execute the search.

Finally, the index value is printed to the console using Console.WriteLine("Index: " + indexPosition); In this case, the output should be Index: 6 since the substring ‘world’ starts at the 6th index of the main string.

It’s worth noting that the index in C# starts from 0. That’s why the index value of the first ‘w’ in ‘world’ is 6 and not 7. It’s also important to remember that IndexOf() is case-sensitive, so it would not find a match for ‘World’ in our main string. If you need to perform a case-insensitive search, you can use IndexOf() in combination with ToLower() or ToUpper().

This simple code snippet and explanation should be enough to help anyone find the index of a substring in a string in C#.

c-sharp