Split Line Based on Given Set of Sub Strings

I thought to share a piece of code which I coded to solve the problem of splitting the line based upon a given set of substrings which is available in the line. The purpose of this program is to get the substring from the line based on the match of the given substring(s) as a key. It will match one of the keys then try to match the same key in the line otherwise move on to the next key and get the starting and ending index, and based on that get the substring from the line. The order of given keys in the  line can be anything. 

  1. private static void Main(string[] args)   
  2. {  
  3.     var parts1 = GetPart(new string[]   
  4.     {  
  5.         "cn=",  
  6.         "ou=",  
  7.         "o="  
  8.     }, 0, "CN=Ming N. Chen/OU=EMPL/OU=MA/O=Verizon@VZNotes".ToLower());  
  9.     var parts2 = GetPart(new string[]  
  10.     {  
  11.         "cn=",  
  12.         "ou=",  
  13.         "o="  
  14.     }, 0, "/o=enron/ou=eu/cn=recipients/cn=adesousa".ToLower());  
  15. }  
  16. private static List < int > NextMatch(string match, int start, string line)  
  17. {  
  18.     List < int > ar = new List < int > ();  
  19.     int j = line.IndexOf(match, start);  
  20.     if (j > -1) {  
  21.         if (!ar.Contains(j))  
  22.         {  
  23.             ar.Add(j);  
  24.         }  
  25.         ar.AddRange(NextMatch(match, j + 1, line));  
  26.     }  
  27.     return ar;  
  28. }  
  29. private static List < string > GetPart(string[] matches, int start, string line)  
  30. {  
  31.     List < int > ar = new List < int > ();  
  32.     List < string > parts = new List < string > ();  
  33.     foreach(var match in matches)   
  34.     {  
  35.         ar.AddRange(NextMatch(match, start, line));  
  36.     }  
  37.     ar.Add(line.Length);  
  38.     int[] Indexes = ar.OrderBy(m => m).ToArray();  
  39.     for (int i = 0; i < Indexes.Length - 1; i++)  
  40.     {  
  41.         parts.Add(line.Substring(Indexes[i], Indexes[i + 1] - Indexes[i]));  
  42.     }  
  43.     return parts;  
  44. }   
 
Ebook Download
View all
Learn
View all