我有一個包含許多線,像這樣的文本文件:分割字符串,並將其分配給字典
花{鬱金香|太陽花|玫瑰}
性別{女|男}
寵物貓{|狗|兔}
我知道如何從文件中讀取行,但什麼是分裂和存儲類別及其子項在字典中的AF的最佳方式terwards?讓我們從包含上述所有行的字符串數組中進行說明?
我有一個包含許多線,像這樣的文本文件:分割字符串,並將其分配給字典
花{鬱金香|太陽花|玫瑰}
性別{女|男}
寵物貓{|狗|兔}
我知道如何從文件中讀取行,但什麼是分裂和存儲類別及其子項在字典中的AF的最佳方式terwards?讓我們從包含上述所有行的字符串數組中進行說明?
的想法使用Key
和value
使用正則表達式是正確的,但我更喜歡使用命名捕獲的可讀性
var regexp = new Regex(@"(?<category>\w+?)\{(?<entities>.*?)\}");
var d = new Dictionary<string, List<string>>();
// you would replace this list with the lines read from the file
var list = new string[] {"Flowers{Tulip|Sun Flower|Rose}"
, " Gender{Female|Male}"
, "Pets{Cat|Dog|Rabbit}"};
foreach (var entry in list)
{
var mc = regexp.Matches(entry);
foreach (Match m in mc)
{
d.Add(m.Groups["category"].Value
, m.Groups["entities"].Value.Split('|').ToList());
}
}
你得到與該類別作爲關鍵一本字典,並在字符串列表中的值
您可以使用此:這個表達式的
string line = reader.ReadLine();
Regex r = new Regex(@"(\w+){(\w+)}");
現在循環後的結果:
foreach(Match m in r.Matches(line)) {
yourDict.Add(m.Groups[1], m.Groups[2].Split(' '));
}
您可以在此代碼
string T = @"Flowers{Tulip|Sun Flower|Rose}
Gender{Female|Male}
Pets{Cat|Dog|Rabbit}";
foreach (var line in T.Split('\n'))//or while(!file.EndOfFile)
{
var S = line.Split(new char[] { '{', '|','}' }, StringSplitOptions.RemoveEmptyEntries);
string Key = S[0];
MessageBox.Show(Key);//sth like this
for (int i = 1 ; i < S.Length; i++)
{
string value = S[i];
MessageBox.Show(value);//sth like this
}
}
你從輸出想要什麼?一個*鍵*和一些*值*? – 2014-09-24 10:39:48
我想添加類別(例如鮮花)作爲listView中的項目,當我選擇我想在第二個listView中顯示子類別(鬱金香,太陽花,玫瑰)的類別。但要知道如何正確地分割它並將其放入字典中將會非常有幫助。 – betaFlux 2014-09-24 10:45:30
是「|」可能值的佔位符,還是文件中的實際字符? – HimBromBeere 2014-09-24 10:51:43