How to split a string in C#

后端 未结 8 858
北海茫月
北海茫月 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:15

    You can do something like this:

                string a = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
                List l_lstValues = new List { "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 :)

提交回复
热议问题