I\'m having a string like
\"List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar\"
and a List
like
You can do something like this:
string a = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
List<String> l_lstValues = new List<string> { "List_1",
"XList_3", "List_2" };
var e = l_lstValues.GetEnumerator();
e.MoveNext();
while(e.MoveNext())
{
var p = a.IndexOf(e.Current);
a = a.Insert(p, "~");
}
var splitStrings = a.Split(new string[]{" ~"},StringSplitOptions.None);
So here, I insert a ~
whenever I encounter a element from the list ( except for the first, hence the outside e.MoveNext()
) and then split on ~
( note the preceding space) The biggest assumption is that you don't have ~
in the string, but I think this solution is simple enough if you can find such a character and ensure that character won't occur in the original string. If character doesn't work for you, use something like ~~@@
and since my solution shows string split with string[]
you can just add the entire string for the split.
Of course you can do something like:
foreach (var sep in l_lstValues)
{
var p = a.IndexOf(sep);
a = a.Insert(p, "~");
}
but that will have an empty string, and I just like using MoveNext()
and Current
:)
Here is a sample code i made. This will get the substring you need provided that your key splitters are sequentially located from left to right of your original string.
var oStr ="List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
List<String> l_lstValues = new List<string> { "List_1", "List_2", "XList_3" };
List<string> splitted = new List<string>();
for(int i = 0; i < l_lstValues.Count; i++)
{
var nextIndex = i + 1 >= l_lstValues.Count ? l_lstValues.Count - 1 : i + 1;
var length = (nextIndex == i ? oStr.Length : oStr.IndexOf(l_lstValues[nextIndex])) - oStr.IndexOf(l_lstValues[i]);
var sub = oStr.Substring(oStr.IndexOf(l_lstValues[i]), length);
splitted.Add(sub);
}