【问题标题】:How to split a string in C#?如何在 C# 中拆分字符串?
【发布时间】:2015-05-09 06:00:12
【问题描述】:

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

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

【问题讨论】:

  • 你得到了什么结果?我猜你有两个 SiteA 作为 item[0] 的项目。
  • 不工作是正常的。您第二次使用 : 进行解析,并且子字符串中有多个 :,因此您最终会丢失“页面”之后的部分,因为您只保留 item 变量的 [0] 和 [1]。

标签: c#


【解决方案1】:

我会为此使用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);
}

【讨论】:

  • 你和我在同一个页面上,除了我使用匿名类型并且你转换为字符串:-)
【解决方案2】:

这是我的解决方案...在 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);
                }
            }

【讨论】:

    【解决方案3】:

    这是我的代码:

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

    【讨论】:

    • 看起来你可能会踩下 SiteA 之前的值?
    • 没关系,我看到你将它附加到上一个!我的错,我收回了:-)
    【解决方案4】:

    我会这样做:

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

    【讨论】:

      【解决方案5】:

      这就是我会做的(测试)。

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

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

      【讨论】:

        【解决方案6】:

        这是使用 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()));
        

        【讨论】:

          【解决方案7】:
          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);
             }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-01-15
            • 2020-11-29
            • 1970-01-01
            • 1970-01-01
            • 2021-08-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多