📜  c# indexof (1)

📅  最后修改于: 2023-12-03 15:13:49.121000             🧑  作者: Mango

C# IndexOf

In C#, the IndexOf method is used to find the index of the first occurrence of a specified substring or character within a string.

Syntax

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 for
  • startIndex - The index to start searching from (optional)
  • value - The character to search for
Return Value

The 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.

Examples
Example 1: Find IndexOf a Substring
string str = "Hello World";
int index = str.IndexOf("World"); // Returns 6
Example 2: Find IndexOf a Character
string str = "Hello World";
int index = str.IndexOf('o'); // Returns 4
Example 3: Find IndexOf a Substring with a Start Index
string str = "Hello World";
int index = str.IndexOf("o", 5); // Returns 7
Example 4: Check if Substring Exists
string str = "Hello World";
bool exists = str.IndexOf("foo") != -1; // Returns false
Conclusion

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.