解析字符串并对其进行拆分的最安全方法
本文关键字:拆分 方法 安全 字符 字符串 串并 | 更新日期: 2023-09-27 18:22:05
我有一个类似的字符串:
UNIQUE_ID-String-TriggerID
82-DEFAULT-4;MINIMODE_ARCADE-1;MINIMODE_RUNNER-4;47-STARLING-1;
一些输入示例:
1) 82-Mode1-4;
2) 4-Arcade-2;9-Runner-2;90-STARLING-1; // here you see Unique ID 4 has two entries
3) 82-DEFAULT-4;MINIMODE_ARCADE-1;MINIMODE_RUNNER-4;47-STARLING-1; 2-DEFAULT-4;MINIMODE_ARCADE-0;
// here 82 UNIQUE ID and 2 UNIQUE ID has two enteritis, but 47 UNIQUE ID has just one enterey
问题是,有时UniqueID47只有一个条目,有时ID82有多个条目。
如何正确拆分和解析字符串?
我将解析后的字符串放入字典中,所以有时我会添加相同的密钥,这会引发异常
我已经完成了以下操作,但仍然无法追踪所有情况:
String data = Encoding.UTF8.GetString(Convert.FromBase64String(Progress));
String[] progressEntries = data.Split(';');
for (int i = 0; i < progressEntries.Length; i++)
{
String entry = progressEntries[i];
String[] values = entry.Split('-');
if (values.Length > 2)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
dict[values[1]] = Convert.ToInt32(values[2]);
Progress.Add(Convert.ToInt32(values[0]), dict);
}
}
}
这还不太清楚,但让我们试一试。在您提供的文本中:
82-DEFAULT-4;MINIMODE_ARCADE-1;MINIMODE_RUNNER-4;47-STARLING-1;
您有两组。每组都有键值对
- 第1组-键:82
- 默认值:4
- 最小代码(_A):1
- MINIMODE_RUNNER:4
- 第2组-键:47
- 八哥:1
如果这是您想要获得的结构,那么一种存储可能性是Dictionary<int,Dictionary<string,int>>
我认为以下代码可以:
public class Parser
{
public Dictionary<int, Dictionary<string, int>> Parse(string input)
{
Dictionary<int, Dictionary<string, int>> data = new Dictionary<int, Dictionary<string, int>>();
int? currentGroupKey = null;
string[] keyValuePairs = input.Split(new char[] { ';' });
foreach (var kvp in keyValuePairs)
{
string[] tokens = kvp.Split(new char[] { '-' });
switch (tokens.Length)
{
case 2:
{
if (currentGroupKey.HasValue)
{
int groupKey = currentGroupKey.Value;
AddKeyValuePair(data, groupKey, tokens[0], tokens[1]);
}
break;
}
case 3:
{
int groupKey;
if (int.TryParse(tokens[0], out groupKey))
{
currentGroupKey = groupKey;
AddKeyValuePair(data, groupKey, tokens[1], tokens[2]);
}
break;
}
default:
break;
}
}
return data;
}
private void AddKeyValuePair(Dictionary<int, Dictionary<string, int>> data, int groupKey, string key, string val)
{
Dictionary<string, int> group;
if (data.ContainsKey(groupKey))
{
group = data[groupKey];
}
else
{
group = new Dictionary<string, int>();
data[groupKey] = group;
}
int intVal;
if (int.TryParse(val, out intVal))
group.Add(key, intVal);
}
}