Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into a dictionary

Tags:

c#

c#-3.0

I have this string

string sx="(colorIndex=3)(font.family=Helvetica)(font.bold=1)"; 

and am splitting it with

string [] ss=sx.Split(new char[] { '(', ')' },     StringSplitOptions.RemoveEmptyEntries); 

Instead of that, how could I split the result into a Dictionary<string,string>? The resulting dictionary should look like:

Key          Value colorIndex   3 font.family  Helvetica font.bold    1 
like image 737
TonyP Avatar asked Dec 05 '09 13:12

TonyP


People also ask

How do I turn a string into a dictionary?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.

Can we convert string to dictionary in Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

How do I split a string in Word?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.


2 Answers

It can be done using LINQ ToDictionary() extension method:

string s1 = "(colorIndex=3)(font.family=Helvicta)(font.bold=1)"; string[] t = s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);  Dictionary<string, string> dictionary =                       t.ToDictionary(s => s.Split('=')[0], s => s.Split('=')[1]); 

EDIT: The same result can be achieved without splitting twice:

Dictionary<string, string> dictionary =            t.Select(item => item.Split('=')).ToDictionary(s => s[0], s => s[1]); 
like image 76
Elisha Avatar answered Sep 20 '22 06:09

Elisha


There may be more efficient ways, but this should work:

string sx = "(colorIndex=3)(font.family=Helvicta)(font.bold=1)";  var items = sx.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)     .Select(s => s.Split(new[] { '=' }));  Dictionary<string, string> dict = new Dictionary<string, string>(); foreach (var item in items) {     dict.Add(item[0], item[1]); } 
like image 30
Fredrik Mörk Avatar answered Sep 22 '22 06:09

Fredrik Mörk