How to split a string in C#

后端 未结 8 919
北海茫月
北海茫月 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条回答
  •  Happy的楠姐
    2021-01-20 00:02

    Here is the most simple and straight-forward solution:

        public static string[] Split(string val, List l_lstValues) {
            var dic = new Dictionary>();
            string curKey = string.Empty;
            foreach (string word in val.Split(' ')) {
                if (l_lstValues.Contains(word)) {
                    curKey = word;
                }
                if (!dic.ContainsKey(curKey))
                    dic[curKey] = new List();
                dic[curKey].Add(word);
            }
            return dic.Values.ToArray();
        }
    

    There is nothing special about the algorithm: it iterates all incoming words and tracks a 'current key' which is used to sort corresponding values into the dictionary.

    EDIT: I simplyfied the original answer to more match the question. It now returns a string[] array - just like the String.Split() method does. An exception will be thrown, if the sequence of incoming strings does not start with a key out of the l_lstValues list.

提交回复
热议问题