📅  最后修改于: 2023-12-03 15:13:49.121000             🧑  作者: Mango
In C#, the IndexOf method is used to find the index of the first occurrence of a specified substring or character within a string.
The syntax for using IndexOf in C# is as follows:
public int IndexOf(string substring)
public int IndexOf(string substring, int startIndex)
public int IndexOf(char value)
public int IndexOf(char value, int startIndex)
substring
- The substring to search forstartIndex
- The index to start searching from (optional)value
- The character to search forThe IndexOf method returns the zero-based index of the first occurrence of the specified substring or character within the calling string. If the substring or character is not found, it returns -1.
string str = "Hello World";
int index = str.IndexOf("World"); // Returns 6
string str = "Hello World";
int index = str.IndexOf('o'); // Returns 4
string str = "Hello World";
int index = str.IndexOf("o", 5); // Returns 7
string str = "Hello World";
bool exists = str.IndexOf("foo") != -1; // Returns false
In conclusion, IndexOf is a useful method for finding the index of the first occurrence of a specified substring or character within a string in C#. It can be used in a variety of ways and is a great addition to any C# programmer's arsenal.