String.IndexOf Method (String)
Reports the zero-based index of the first occurrence of the specified String in this instance.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- value
- Type: System.String
The String to seek.
Return Value
Type: System.Int32The zero-based index position of value if that string is found, or -1 if it is not. If value is Empty, the return value is 0.
| Exception | Condition |
|---|---|
| ArgumentNullException | value is null. |
The following example uses the IndexOf method to determine the starting position of an animal name in a sentence. It then uses this position to insert an adjective that describes the animal into the sentence.
using System; public class InsertTest { public static void Main() { string animal1 = "fox"; string animal2 = "dog"; string strTarget = String.Format("The {0} jumped over the {1}.", animal1, animal2); Console.WriteLine("The original string is:{0}{1}{0}", Environment.NewLine, strTarget); Console.Write("Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal1); string adj1 = Console.ReadLine(); Console.Write("Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal2); string adj2 = Console.ReadLine(); adj1 = adj1.Trim() + " "; adj2 = adj2.Trim() + " "; strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1); strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2); Console.WriteLine("{0}The final string is:{0}{1}", Environment.NewLine, strTarget); } } // Output from the example might appear as follows: // The original string is: // The fox jumped over the dog. // // Enter an adjective (or group of adjectives) to describe the fox: ==> bold // Enter an adjective (or group of adjectives) to describe the dog: ==> lazy // // The final string is: // The bold fox jumped over the lazy dog.
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.