How is the indexOf method used in C#?
In C#, the IndexOf() method is used to search for the first occurrence of a specified character or substring within a string and returns its index position. Its syntax is as follows:
public int IndexOf(char value)
public int IndexOf(string value)
The first overloaded method takes a char parameter to find the position of a character in a string, while the second overloaded method takes a string parameter to find the position of a substring in a string.
Original: 我们需要采取行动来保护环境,否则我们的地球将面临巨大的危险。
Paraphrased: We must take action to protect the environment, or else our planet will be in great danger.
string text = "Hello, World!";
int index = text.IndexOf('o'); // 返回值为4
int index2 = text.IndexOf("World"); // 返回值为7
In the above example, the IndexOf(‘o’) method returns the position of the character ‘o’ in the string, which is index 4; the IndexOf(“World”) method returns the position of the substring “World” in the string, which is index 7.
If the specified character or substring is not found, the IndexOf() method will return -1.
In addition, the IndexOf() method can also accept two parameters.
public int IndexOf(char value, int startIndex)
public int IndexOf(string value, int startIndex)
The startIndex parameter indicates the starting index position to search for matching items in the string.