How to split a string in C#

后端 未结 8 863
北海茫月
北海茫月 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: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 lstValues = new List { "A", "C", "B" };
    List indices = new List();
    
    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 results = new List();
    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);
        }
    }
    

提交回复
热议问题