The usage of IndexOf LastIndexOf IndexOfAny and LastIndexOfAny of asp.net

  • 2020-05-17 05:15:06
  • OfStack

To locate a substring is to look for a substring or a character in a string.

1. IndexOf/LastIndexOf

The IndexOf method is used to search for the first occurrence of a particular character or substring in a string. It is case sensitive and counts at 0 from the first character of the string. If the string does not contain this character or substring, -1 is returned. The common overloaded form is shown below.

Positioning character

int IndexOf (char value)

int IndexOf(char value, int startIndex)

int IndexOf(char value, int startIndex, int count)

Locate the substring

int IndexOf (string value)

int IndexOf(string value, int startIndex)

int IndexOf(string value, int startIndex, int count)

In the above overloaded form, the parameters have the following meanings:

value: character or substring to be determined.

startIndex: the actual location to start searching in the total string.

count: the number of characters in the total string searched from the beginning.

The following code looks for the first occurrence of the character 'l' in' Hello '.

Code 4-7 USES IndexOf to find the first occurrence of the character: Default.aspx.cs

1. String s Hello = "";

2. int I = s. IndexOf(' l')); / / 2

Similar to IndexOf, LastIndexOf is used to search for the last occurrence of a particular character or substring in a string. Its method definition and return value are the same as IndexOf.

2. IndexOfAny/LastIndexOfAny

The IndexOfAny method has similar functionality to IndexOf, except that it can search for the first occurrence of any character in a string in an array of 1 characters. Again, this method is case sensitive and counts at 0 starting with the first character of the string. If the string does not contain this character or substring, -1 is returned. There are three common overloaded forms of IndexOfAny:

(1) int IndexOfAny(char[]anyOf);

(2) int IndexOfAny(char[]anyOf, int startIndex);

(3) int IndexOfAny(char[]anyOf, int startIndex, int count)

In the above overloaded form, the parameters have the following meanings:

(1) anyOf: undetermined bit character array, the method will return the first occurrence of any 1 character in this array.

(2) startIndex: the actual position where the search began in the original string.

(3) count: the number of characters searched from the starting position in the original string.

The following example looks for the first and last occurrence of the character 'l' in' Hello '.

Code 4-8 USES IndexOfAny to find the first and last occurrence of the substring: Default.aspx.cs

1. String s = "Hello";

2. char [] anyOf = {' H ', 'e', 'l'};

3. int i1 = s. IndexOfAny (anyOf)); / / 0

4. int i2 = s. LastIndexOfAny (anyOf)); / / 3

Similar to IndexOfAny, LastIndexOfAny is used to search for the last occurrence of any character in a string in an array of 1 character.

Related articles: