开发者

How to split a string in C#

开发者 https://www.devze.com 2023-03-04 01:49 出处:网络
I\'m having a string like \"List_1 fooo asdf List_2 bar fdsa XLis开发者_如何学运维t_3 fooo bar\"

I'm having a string like

"List_1 fooo asdf List_2 bar fdsa XLis开发者_如何学运维t_3 fooo bar"

and a List<String> like

 List<String> l_lstValues = new List<string> { "List_1", "XList_3", "List_2" };

I need to split the string based on the value in the l_lstValues.

So the splitted substrings will be like

List_1 fooo asdf 
List_2 bar fdsa 
XList_3 fooo bar

Please post me a way to do this Thanks in advance


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


You can do something like this:

            string a = "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" };

            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 :)


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.


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(':');


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.


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);
    }
}


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

        List<string> splitted = new List<string>();
        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);
        }


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

精彩评论

暂无评论...
验证码 换一张
取 消