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.
- private static void Main(string[] args)
- {
- var parts1 = GetPart(new string[]
- {
- "cn=",
- "ou=",
- "o="
- }, 0, "CN=Ming N. Chen/OU=EMPL/OU=MA/O=Verizon@VZNotes".ToLower());
- var parts2 = GetPart(new string[]
- {
- "cn=",
- "ou=",
- "o="
- }, 0, "/o=enron/ou=eu/cn=recipients/cn=adesousa".ToLower());
- }
- private static List < int > NextMatch(string match, int start, string line)
- {
- List < int > ar = new List < int > ();
- int j = line.IndexOf(match, start);
- if (j > -1) {
- if (!ar.Contains(j))
- {
- ar.Add(j);
- }
- ar.AddRange(NextMatch(match, j + 1, line));
- }
- return ar;
- }
- private static List < string > GetPart(string[] matches, int start, string line)
- {
- List < int > ar = new List < int > ();
- List < string > parts = new List < string > ();
- foreach(var match in matches)
- {
- ar.AddRange(NextMatch(match, start, line));
- }
- ar.Add(line.Length);
- int[] Indexes = ar.OrderBy(m => m).ToArray();
- for (int i = 0; i < Indexes.Length - 1; i++)
- {
- parts.Add(line.Substring(Indexes[i], Indexes[i + 1] - Indexes[i]));
- }
- return parts;
- }