I wrote my own extension method in C #, which is an improvement on the extensionmethod [] getBetweenAll line (line source, startstring line, endstring line);
Initially, this extension method found all substrings between two lines, for example:
string source = "<1><2><3><4>";
source.getBetweenAll("<", ">");
//output: string[] {"1", "2", "3", "4"}
But if you had another occurrence <at the beginning it just will be between this and the whole line
string source = "<<1><2><3><4>";
source.getBetweenAll("<", ">");
//output: string[] {"<1><2><3><4"}
So, I rewrote it more accurately and searched back with ">" to find the first occurrence of "<"
Now it works for me, but the problem is that it is too slow , because the search method skips every character of the entire string for each event. Do you know how I could improve the speed of this feature? Or is it impossible?
http://pastebin.com/JEZmyfSG
,
public static List<int> IndexOfAll(this string main, string searchString)
{
List<int> ret = new List<int>();
int len = searchString.Length;
int start = -len;
while (true)
{
start = main.IndexOf(searchString, start + len);
if (start == -1)
{
break;
}
else
{
ret.Add(start);
}
}
return ret;
}
public static string[] getBetweenAll(this string main, string strstart, string strend, bool preserve = false)
{
List<string> results = new List<string>();
List<int> ends = main.IndexOfAll(strend);
foreach (int end in ends)
{
int start = main.previousIndexOf(strstart, end);
results.Add(main.Substring(start, end - start) + (preserve ? strend : string.Empty));
}
return results.ToArray();
}
public static int previousIndexOf(this string main, string find, int offset)
{
int wtf = main.Length ;
int x = main.LastIndexOf(find, wtf);
while (x > offset)
{
x = main.LastIndexOf(find, wtf);
wtf -= 1;
}
return x;
}
, PreviousIndexOf (string, int searchfrom); . IndexOf(),