Here, we use IndexOf to see if a string contains a word. We test the string for a substring "Man" We test the result of IndexOf against the special constant -1.
Example:
IndexOf returns the location of the string "Man" It is not equal to -1. So the line is written to the console window.
Usually we want to know the exact result of IndexOf. We can store its result in an int local.
Based on: .NET 4.5 C# program that uses IndexOf
- using System;
- class Program1
- {
- static void Main()
- {
-
- const string value = "Man is cute.";
-
- if (value.IndexOf("Man") != -1)
- {
- Console.WriteLine("string contains Man!");
- }
- }
- }
Output:
string contains Man!