-
-
Save Nyconing/c67dda0555781abb34a4dd4751290672 to your computer and use it in GitHub Desktop.
Review first, Use at your own risk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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