Find The Position Of The First Occurrence Of A Substring In A String In C#
Code snippet for how to Find The Position Of The First Occurrence Of A Substring In A String In C# with sample and detail explanation
Finding the position of the first occurrence of a substring in a string is a commonly required operation in programming tasks. This short article will demonstrate how you can achieve this using C#.
Code snippet to Find The Position Of The First Occurrence Of A Substring In A String
string mainString = "Hello World Csharp Tutorial";
string subString = "Csharp";
int position = mainString.IndexOf(subString);
Console.WriteLine(position);
Code Explanation For Finding The Position Of The First Occurrence Of A Substring In A String.
Let’s breakdown the code to understand it better.
-
string mainString = "Hello World Csharp Tutorial";
Here, we define a variable ‘mainString’ that holds our main string. -
string subString = "Csharp";
Similarly, we define another string ‘subString’. This string is what we’ll be searching for in our main string. -
int position = mainString.IndexOf(subString);
The ‘IndexOf()’ function is a built-in method in C# that returns the index of the first occurrence of a specified substring. If the substring is not found, it returns -1. We pass the ‘subString’ to ‘IndexOf()’ function, called from ‘mainString’. The result (position of the first occurrence of the substring in the main string) is stored in the integer variable ‘position’. -
Console.WriteLine(position);
Finally, we print the result to the console. If ‘subString’ is found in ‘mainString’, the output will be the zero-based index of the first occurrence of the subString within the mainString. If not found, the output will be -1.
This simple yet powerful method allows you to find the position of the first occurrence of a substring within a main string in C#, thus making your coding tasks easier.