How to split a string in C#

后端 未结 8 859
北海茫月
北海茫月 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-19 23:59

    You have to use this split method on msdn, you have to pass your List into an array and then, you have to pass as a parameter of the split that array.

    I leave you the link here

    http://msdn.microsoft.com/en-us/library/tabh47cf(v=VS.90).aspx

    If you want to mantain the words you're splitting with, you will have to iterate the resulted array and then add the words in your list, if you have the same order in the string and in the list.

    If the order is unknown, you mus use indexOf to locate the words in the list and split the string manually.

    See you

    0 讨论(0)
  • 2021-01-20 00:02

    Here is the most simple and straight-forward solution:

        public static string[] Split(string val, List<string> l_lstValues) {
            var dic = new Dictionary<string, List<string>>();
            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<string>();
                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.

    0 讨论(0)
  • 2021-01-20 00:05

    You can use following code achieving this task

            string str = "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" };
    
            string[] strarr = str.Split(' ');
            string sKey, sValue;
            bool bFlag = false;
            sKey = sValue = string.Empty;
    
            var lstResult = new List<KeyValuePair<string, string>>();
    
            foreach (string strTempKeys in l_lstValues)
            {
                bFlag = false;
                sKey = strTempKeys;
                sValue = string.Empty;
    
                foreach (string strTempValue in strarr)
                {
                    if (bFlag)
                    {
                        if (strTempValue != sKey && l_lstValues.Contains(strTempValue))
                        {
                            bFlag = false;
                            break;
                        }
                        else
                            sValue += strTempValue;
                    }
                    else if (strTempValue == sKey)
                        bFlag = true;
                }
    
                lstResult.Add(new KeyValuePair<string, string>(sKey, sValue));                
            }
    
    0 讨论(0)
  • 2021-01-20 00:10

    You can replace every string of the list in the original string with an added control character, and then split on that caracter. For instance, your original string:

    List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar
    

    Need to become:

    List_1 fooo asdf;List_2 bar fdsa;XList_3 fooo bar
    

    Which will later be split based on ;, producing the desired result. For that, i use this code:

    string ori = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar" 
    foreach (string word in l_lstValues) {
        ori = ori.Replace(word, ";" + word);
    }
    ori = ori.Replace(" ;", ";"); // remove spaces before ;
    ori = Regex.Replace(ori, "^;", ""); // remove leading ;
    return (ori.split(";"));
    

    You could also assemble the following regular expression:

    (\S)(\s?(List_1|XList_3|List_2))
    

    The first token (\S) will prevent replacing the first occurrence, and the second token \s? will remove the space. Now we use it to add the ;:

    string ori = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar" 
    string regex = "(\S)(\s?(" + String.Join("|", l_lstValues) + "))";
    ori = Regex.Replace(ori, regex, "$1;$3");
    return (ori.split(";"));
    

    The regex option is a bit more dangerous because the words can contain scape sequences.

    0 讨论(0)
  • 2021-01-20 00:13

    You could do something like below:

    string sampleStr = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
    string[] splitStr = 
       sampleStr.Split(l_lstValues.ToArray(), StringSplitOptions.RemoveEmptyEntries);
    

    EDIT: Modified to print the fragments with list word as well

    Assumption: There is no ':' in sampleStr

    foreach(string listWord in l_lstValues)
    {
        sampleStr = sampleStr.Replace(listWord, ':'+listWord);
    }
    string[] fragments = sampleStr.Split(':');
    
    0 讨论(0)
  • 2021-01-20 00:14

    You can use the String.IndexOf method to get the index of the starting character for each phrase in your list.

    Then, you can use this index to split the string.

    string input = "A foo bar B abc def C opq rst";
    List<string> lstValues = new List<string> { "A", "C", "B" };
    List<int> indices = new List<int>();
    
    foreach (string s in lstValues)
    {
        // find the index of each item
        int idx = input.IndexOf(s);
    
        // if found, add this index to list
        if (idx >= 0)
           indices.Add(idx);        
    }
    

    Once you have all the indices, sort them:

    indices.Sort();
    

    And then, use them to get resulting strings:

    // obviously, if indices.Length is zero,
    // you won't do anything
    
    List<string> results = new List<string>();
    if (indices.Count > 0)
    {
        // add the length of the string to indices
        // as the "dummy" split position, because we
        // want last split to go till the end
        indices.Add(input.Length + 1);
    
        // split string between each pair of indices
        for (int i = 0; i < indices.Count-1; i++)
        {
            // get bounding indices
            int idx = indices[i];
            int nextIdx = indices[i+1];
    
            // split the string
            string partial = input.Substring(idx, nextIdx - idx).Trim();
    
            // add to results
            results.Add(partial);
        }
    }
    
    0 讨论(0)
提交回复
热议问题