如何在C#中拆分字符串?

时间:2011-07-07 21:09:13

标签: c#

我正在尝试解析以下字符串并获取结果。

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6"

我想在拆分后得到以下结果。

string SiteA = "Pages:1,Documents:6"
string SiteB = "Pages:4"

这是我的代码,但它似乎不起作用。如何获得所有相关的“SiteA”和“SiteB”?

List<string> listItem = new List<string>();
string[] keyPairs = test.Split(',');
string[] item;
foreach (string keyPair in keyPairs)
{
    item = keyPair.Split(':');
    listItem.Add(string.Format("{0}:{1}", item[0].Trim(), item[1].Trim()));
}

7 个答案:

答案 0 :(得分:3)

我会使用Lookup

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";
var listItemsBySite = test.Split(',')
                          .Select(x => x.Split(':'))
                          .ToLookup(x => x[0], 
                                    x => string.Format("{0}:{1}", 
                                                       x[1].Trim(), 
                                                       x[2].Trim()));

然后您可以像这样使用它:

foreach (string item in listItemsBySite["SiteA"])
{
    Console.WriteLine(item);
}

答案 1 :(得分:1)

这是我的解决方案......在LINQ中非常优雅,您可以使用匿名对象,元组,KeyValuePair或您自己的自定义类。我只是使用匿名类型。

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";

            var results = test
                .Split(',')
                .Select(item => item.Split(':'))
                .ToLookup(s => s[0], s => new { Key = s[1], Value = s[2] });

            // This code just for display purposes
            foreach (var site in results)
            {
                Console.WriteLine("Site: " + site.Key);

                foreach (var value in site)
                {
                    Console.WriteLine("\tKey: " + value.Key + " Value: " + value.Value);
                }
            }

答案 2 :(得分:0)

这是我的代码:

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";
string[] data = test.Split(',');
Dictionary<string, string> dic = new Dictionary<string, string>();
for(int i = 0; i < data.Length; i++) {
    int index = data[i].IndexOf(':');
    string key = data[i].Substring(0, index);
    string value = data[i].Substring(index + 1);
    if(!dic.ContainsKey(key))
        dic.Add(key, value);
    else
        dic[key] = string.Format("{0}, {1}", new object[] { dic[key], value }); 
}

答案 3 :(得分:0)

我将如何做到这一点:

SortedList<string, StringBuilder> listOfLists = new SortedList<string, StringBuilder>();
string[] keyPairs = test.Split(',');
foreach (string keyPair in keyPairs)
{
    string[] item = keyPair.Split(':');
    if (item.Length >= 3)
    {
        string nextValue = string.Format("{0}:{1}", item[1].Trim(), item[2].Trim());
        if (listOfLists.ContainsKey(item[0]))
            listOfLists[item[0]].Append(nextValue);
        else
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(nextValue);
            listOfLists.Add(item[0], sb);
        }
    }
}

foreach (KeyValuePair<string, StringBuilder> nextCollated in listOfLists)
    System.Console.WriteLine(nextCollated.Key + ":" + nextCollated.Value.ToString());

答案 4 :(得分:0)

这就是我要做的(测试过的)。

(但是,假设所有项目都将正确格式化)。 当然,它并没有真正优化。

static void Main(string[] args)
{

    string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";

    Dictionary<String, List<String>> strings = new Dictionary<string, List<string>>();

    String[] items = test.Split(',');

    foreach (String item in items)
    {
        List<String> itemParts = item.Split(':').ToList();
        String firstPart = itemParts[0];

        itemParts.RemoveAt(0);
        String secondPart = String.Join(":", itemParts);

        if (!strings.ContainsKey(firstPart))
            strings[firstPart] = new List<string>();

        strings[firstPart].Add(secondPart);
    }


    // This is how you would consume it
    foreach (String key in strings.Keys)
    {
        List<String> keyItems = strings[key];
        Console.Write(key + ": ");

        foreach (String item in keyItems)
            Console.Write(item + " ");
        Console.WriteLine();
    }

}

答案 5 :(得分:0)

这是使用LINQ的解决方案:

string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";

var dict = test
           .Split(',')
           .GroupBy(s => s.Split(':')[0])
           .ToDictionary(g => g.Key,
                         g => string.Join(",", 
                                  g.Select(i => string.Join(":", i.Split(':').Skip(1)))
                                   .ToArray()));

答案 6 :(得分:0)

using System;
using System.Linq;
using System.Text.RegularExpressions;

class MyClass
{
   static void Main(string[] args)
   {
       string test = "SiteA:Pages:1,SiteB:Pages:4,SiteA:Documents:6";
       var sites = test.Split(',')
           .Select(p => p.Split(':'))
           .Select(s => new { Site = s[0], Key = s[1], Value = s[2] })
           .GroupBy(s => s.Site)
           .ToDictionary(g => g.Key, g => g.ToDictionary(e => e.Key, e => e.Value));

       foreach (var site in sites)
           foreach (var key in site.Value.Keys)
               Console.WriteLine("Site {0}, Key {1}, Value {2}", site.Key, key, site.Value[key]);

       // in your preferred format:
       var SiteA = string.Join(",", sites["SiteA"].Select(p => string.Format("{0}:{1}", p.Key, p.Value)));
       var SiteB = string.Join(",", sites["SiteB"].Select(p => string.Format("{0}:{1}", p.Key, p.Value)));

       Console.WriteLine(SiteA);
       Console.WriteLine(SiteB);
   }
}