How to split a string in C#

后端 未结 8 871
北海茫月
北海茫月 2021-01-19 23:22

I\'m having a string like

\"List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar\"

and a List like



        
8条回答
  •  广开言路
    2021-01-20 00:17

    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 l_lstValues = new List { "List_1", "List_2", "XList_3" };
    
            List splitted = new List();
            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);
            }
    

提交回复
热议问题