C#中如何分割字符串

发布于 2024-11-05 12:58:48 字数 437 浏览 0 评论 0原文

我有一个类似

"List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar"

List 的字符串,就像

 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

请给我一个方法来做到这一点 提前致谢

I'm having a string like

"List_1 fooo asdf List_2 bar fdsa XList_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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

白昼 2024-11-12 12:58:49

你可以这样做:

            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() )然后分割 ~ (注意前面的空格)最大的假设是字符串中没有 ~ ,但我认为这个解决方案足够简单,如果你可以找到这样的角色并确保该角色不会出现在原作中 细绳。如果字符不适合您,请使用类似 ~~@@ 的内容,因为我的解决方案显示用 string[] 分割字符串,您只需添加整个字符串即可分裂。

当然你可以这样做:

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

        }

但这将有一个空字符串,我只是喜欢使用 MoveNext()Current :)

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

用心笑 2024-11-12 12:58:49

您可以使用添加的控制字符替换原始字符串中列表中的每个字符串,然后根据该字符进行拆分。例如,您的原始字符串:

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 序列。

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.

平生欢 2024-11-12 12:58:49

您可以执行如下操作:

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

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(':');
清醇 2024-11-12 12:58:49

这是最简单直接的解决方案:

    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 列表中的键开头,则会引发异常。

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.

撩心不撩汉 2024-11-12 12:58:49

您可以使用 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);
    }
}

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);
    }
}
阳光下的泡沫是彩色的 2024-11-12 12:58:49

这是我制作的示例代码。如果您的键拆分器按顺序位于原始字符串的从左到右,这将获得您需要的子字符串。

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

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);
        }
小伙你站住 2024-11-12 12:58:49

您可以使用以下代码来完成此任务

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

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));                
        }
朮生 2024-11-12 12:58:48

你必须在msdn上使用这个split方法,你必须将你的List传递到一个数组中,然后,你必须作为split该数组的参数传递。

我将链接留在这里

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

如果您想保留要分割的单词,则必须迭代结果数组,然后添加单词在您的列表中,如果字符串和列表中的顺序相同。

如果顺序未知,则必须使用indexOf来定位列表中的单词并手动拆分字符串。

再见

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文