Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Review first, Use at your own risk
public class CommonDictionaryParser {
public CommonDictionaryParser(string dict) {
DictionaryString = dict;
ParseToDictionary();
}
public CommonDictionaryParser(Dictionary<string, string> dict) {
Dictionary = dict;
}
public string DictionaryString;
public Dictionary<string, string> Dictionary;
public char PairSeparator = ';';
public char KeySeparator = '=';
public void ParseToDictionary() {
Dictionary = new Dictionary<string, string>();
if (string.IsNullOrEmpty(DictionaryString) || DictionaryString.Length < 5) return;
var key = new StringBuilder();
var value = new StringBuilder();
var status = 0; // 0=key, 1=keyseparator, 2=value, 3=pairseparator
for (var i = 0; i < DictionaryString.Length; i++) {
var currentChar = DictionaryString[i];
switch (status) {
case 0:
key.Append(currentChar);
if (i + 1 < DictionaryString.Length && DictionaryString[i + 1] == KeySeparator) {
status = 1;
}
break;
case 1:
status = 2;
break;
case 2:
value.Append(currentChar);
if (i + 1 < DictionaryString.Length && DictionaryString[i + 1] == PairSeparator) {
status = 3;
Dictionary.Add(key.ToString(), value.ToString());
key = new StringBuilder();
value = new StringBuilder();
}
else if (i + 1 == DictionaryString.Length) {
status = 3;
Dictionary.Add(key.ToString(), value.ToString());
key = new StringBuilder();
value = new StringBuilder();
}
break;
case 3:
status = 0;
break;
}
}
}
public new string ToString() {
return string.Join(PairSeparator.ToString(), Dictionary.Select(x => x.Key + KeySeparator + x.Value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.