我有一个字符串,我将其与'*'分开,然后将其存储到Hashtable
ht1。
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
string[] words = fString.Split('*');
int i = 0;
Hashtable ht1 = new Hashtable();
foreach(string s in words) {
ht1.Add(i,s);
i++;
}
然后我从中删除一些字符并将其存储到另一个Hashtable
,ht2
Hashtable ht2 = new Hashtable();
int j = 0;
for (int t = 0; t < ht1.Count; t++)
{
String str = ht1[t].ToString();
string str2 = str.Substring(7);
Console.WriteLine("str2:" + str2);
ht2.Add(j, str2);
j++;
}
int count = ht2.Count;
ht2.Remove(0);
ht2.Remove(count-1);
结果是这样的:
20_30_90
15.5_20.1_35.0
40_230_110
但我只需在Hashtable
中存储数字。像这样:
k = 1 | 20.0 | 30.0 | 90.0
k = 2 | 15.5 | 20.1 | 35.0
k = 3 | 40.0 | 230.0 | 110.0
我该怎么办?我尝试使用'_'分割,但它不起作用,也许我的语法错了?
答案 0 :(得分:1)
这也可以起作用:
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
var items = fString.Split('*');
var values = items.ToList().Select(s => s.Substring(7).Split('_'));
var hash = new Hashtable();
var i=0;
values.ToList().ForEach(v => hash.Add(++i, String.Join("|", v)));
和转储输出(来自LinqPad)是:
Key Value
5 END
4 40|230|110
3 15.5|20.1|35.0
2 20|30|90
1 ACK
修改
...并将值打印到控制台
foreach (var key in hash.Keys)
{
Console.WriteLine("{0}: {1}", key, hash[key]);
}
答案 1 :(得分:0)
如果你使用Split('_')
应该没问题。
另一种方法是使用正则表达式:
for(int cnt = 1 ....) {
Regex rex = new Regex(@"\d+(\.\d+)?");
MatchCollection mac = rex.Matches("your string of numbers");
string string4Hash = string.Format("{0}", cnt);
foreach (Match match in mac)
{
string4Hash = string.Format("{0}|{1}", string4Hash, double.Parse(match.Value));
}
}
答案 2 :(得分:0)
如果不将中间结果存储在哈希表中,您可以减少复杂性,不需要这样做。此外,我建议使用类型安全的集合,Linq真的有帮助。所以我建议这段代码:
String fString = "DAVCFW_ACK*DAVCFW_20_30_90*DAVCFW_15.5_20.1_35.0*DAVCFW_40_230_110*DAVCFW_END";
var words = fString.Split('*');
var dictionary = new Dictionary<int, List<double>>();
for (int i = 1; i != words.Length - 1; i++) {
var numbers = words[i].Split('_')
.Skip(1)
.Select(n => Double.Parse(n))
.ToList();
dictionary.Add(i, numbers);
}
测试它:
foreach (var key in dictionary.Keys) {
Console.WriteLine(key);
foreach (double number in dictionary[key]) {
Console.WriteLine(" " + number);
}
}
产生正确的结果: