C# Code to Find Count of Sub-string Occurrences

Using IndexOf: 
  1. string MyString = "OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com";  
  2. string stringToFind = "OU=";  
  3.   
  4. List<int> positions = new List<int>[];  
  5. int pos = 0;  
  6. while ((pos < MyString.Length) && (pos = MyString.IndexOf(stringToFind, pos)) != -1)  
  7. {  
  8.     positions.Add(pos);  
  9.     pos += stringToFind.Length();  
  10. }  
  11.   
  12. Console.WriteLine("{0} occurrences", positions.Count);  
  13. foreach (var p in positions)  
  14. {  
  15.     Console.WriteLine(p);  
  16. }  
Using Regex: 
  1. var matches = Regex.Matches(MyString, "OU=");  
  2. Console.WriteLine("{0} occurrences", matches.Count);  
  3. foreach (var m in matches)  
  4. {  
  5.     Console.WriteLine(m.Index);  
  6. }