2011-07-07 99 views
3

我想解析下面的字符串並得到結果。如何在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())); 
} 
+0

你得到什麼樣的結果?我猜想你有兩個與SiteA作爲項目[0]的項目。 – Narnian

+0

什麼版本的.NET? –

+0

這是正常的,它不工作。第二次使用:進行解析,並且有多個:在子字符串中,所以最終會丟失「Pages」之後的部分,因爲只保留item變量的[0]和[1]。 – Tipx

回答

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

看起來像你可能跺腳SiteA以前的價值? –

+0

它在這裏工作得很好:) – platon

+0

沒關係,我看到你將它追加到以前!我的壞,我收回:-) –

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

你和我在同一頁,除了我用匿名類型,你轉換爲一個字符串:-) –

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

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