簡體   English   中英

如何在C#中拆分字符串

[英]How to split a string in C#

我有一個字符串

"List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar"

List<String>一樣

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

我需要根據l_lstValues的值拆分字符串。

所以分裂的子串就像

List_1 fooo asdf 
List_2 bar fdsa 
XList_3 fooo bar

請給我發一個方法來提前謝謝

你必須在msdn上使用這種拆分方法,你必須將List傳遞給一個數組,然后,你必須作為拆分該數組的參數傳遞。

我給你留下這里的鏈接

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

如果你想保留你正在拆分的單詞,你必須迭代結果數組,然后在列表中添加單詞,如果你在字符串和列表中有相同的順序。

如果訂單未知,您可以使用indexOf查找列表中的單詞並手動拆分字符串。

再見

您可以執行以下操作:

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

編輯 :修改以打印帶有列表單詞的片段

假設sampleStr沒有' : '

foreach(string listWord in l_lstValues)
{
    sampleStr = sampleStr.Replace(listWord, ':'+listWord);
}
string[] fragments = sampleStr.Split(':');

這是最簡單直接的解決方案:

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

該算法沒有什么特別之處:它迭代所有傳入的單詞並跟蹤“當前鍵”,用於將相應的值排序到字典中。

編輯:我簡單地回答了原來的答案以更符合這個問題。 它現在返回一個string []數組 - 就像String.Split()方法一樣。 如果傳入字符串序列不是以l_lstValues列表中的鍵開頭,則拋出異常。

您可以使用添加的控制字符替換原始字符串中列表的每個字符串,然后在該字符上拆分。 例如,您的原始字符串:

List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar

需要成為:

List_1 fooo asdf;List_2 bar fdsa;XList_3 fooo bar

以后將基於分割; ,產生預期的結果。 為此,我使用此代碼:

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(";"));

您還可以匯編以下正則表達式:

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

第一個令牌(\\S)將阻止替換第一個匹配,第二個令牌\\s? 將刪除空間。 現在我們用它來添加;

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(";"));

正則表達式選項更危險,因為單詞可以包含scape序列。

你可以這樣做:

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

所以在這里,我插入一個~每當我遇到一個列表中的元素(除了第一個,因此外面的e.MoveNext() )然后拆分~ (注意前面的空格)最大的假設是你沒有在字符串中有~ ,但我認為這個解決方案很簡單,如果你能找到這樣的字符並確保字符不會出現在原始字符串中。 如果字符對你不起作用,請使用~~@@類的東西,因為我的解決方案顯示字符串split with string[]你可以添加整個字符串進行拆分。

當然你可以這樣做:

foreach (var sep in l_lstValues)
        {
            var p = a.IndexOf(sep);
            a = a.Insert(p, "~");

        }

但是這將有一個空字符串,我只是喜歡使用MoveNext()Current :)

您可以使用String.IndexOf方法獲取列表中每個短語的起始字符的索引。

然后,您可以使用此索引來拆分字符串。

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

獲得所有索引后,對它們進行排序:

indices.Sort();

然后,使用它們來獲得結果字符串:

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

這是我制作的示例代碼。 如果您的鍵分割器從原始字符串的左側到右側順序排列,這將獲得您需要的子字符串。

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

您可以使用以下代碼完成此任務

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM