Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to find the index of a word in a string
Finding the index of a word in a string or array is a common programming task in C#. The Array.IndexOf() method provides an efficient way to locate the position of a specific element within an array of strings.
Syntax
Following is the syntax for using Array.IndexOf() method −
int index = Array.IndexOf(array, searchValue);
Parameters
- array − The one-dimensional array to search
- searchValue − The object to locate in the array
Return Value
The method returns the index of the first occurrence of the specified value. If the value is not found, it returns -1.
Using Array.IndexOf() to Find Word Index
Declare and initialize an array −
string[] str = new string[] {
"Cat",
"Mat",
"Rat"
};
Now, use IndexOf() method to find the index of the word "Mat" −
Array.IndexOf(str, "Mat");
Example
using System;
public class Demo {
public static void Main() {
string[] str = new string[] {
"Cat",
"Mat",
"Rat"
};
Console.WriteLine("Our Array =");
for (int i = 0; i < str.Length; i++) {
string res = str[i];
Console.WriteLine(res);
}
int findIndex = Array.IndexOf(str, "Mat");
Console.Write("Element Mat found at the following index: ");
Console.WriteLine(findIndex);
}
}
The output of the above code is −
Our Array = Cat Mat Rat Element Mat found at the following index: 1
Finding Index in a String Using String.IndexOf()
For finding a word within a single string, use the String.IndexOf() method −
Example
using System;
public class StringIndexDemo {
public static void Main() {
string sentence = "The quick brown fox jumps over the lazy dog";
string searchWord = "brown";
int index = sentence.IndexOf(searchWord);
if (index != -1) {
Console.WriteLine("Word '{0}' found at index: {1}", searchWord, index);
} else {
Console.WriteLine("Word '{0}' not found", searchWord);
}
}
}
The output of the above code is −
Word 'brown' found at index: 10
Handling Case When Word Is Not Found
Example
using System;
public class IndexNotFoundDemo {
public static void Main() {
string[] animals = {"Dog", "Cat", "Bird", "Fish"};
string searchAnimal = "Lion";
int index = Array.IndexOf(animals, searchAnimal);
if (index == -1) {
Console.WriteLine("'{0}' not found in the array", searchAnimal);
} else {
Console.WriteLine("'{0}' found at index: {1}", searchAnimal, index);
}
}
}
The output of the above code is −
'Lion' not found in the array
Conclusion
The Array.IndexOf() method efficiently finds the index of a word in a string array, returning -1 if not found. For searching within a single string, use String.IndexOf(). Always check for -1 to handle cases where the search term is not present.
