C# IndexOf

IndexOf is a method of many classes and data types, including string, List, ArrayList etc.
Get the position of substring of a string.

string s = "endmemo csharp tutorial";
int p = s.IndexOf('n'); //1
int p2 = s.IndexOf(' '); //7, 1st occurrence
int p3 = s.IndexOf('me'); //3
int p4 = s.IndexOf('med'); //-1, not exist
//get the 2nd occurrence of letter e
int p = s.IndexOf('e');
int p2 = s.Length;
if (p < s.Length) p2 = s.IndexOf('e', p+1); //4

Get the position of substring of a string ignore case.
string s = "Endmemo csharp tutorial";
int p = s.IndexOf("e",System.StringComparison.OrdinalIgnoreCase); //0

Check the position of an element in a List.
using System.Collections.Generic;
List<string> lst = new List<string>();
int p = lst.IndexOf("Tuesday"); //1

Check whether the ArrayList has a specific element.
using System.Collections;
ArrayList al = new ArrayList();
int num = al.IndexOf("Tuesday"); //1

endmemo.com © 2017  Terms of Use | Home