In this example, i’ll show you How to split a string to key value pairs in C# Windows Form Application.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
private void button1_Click(object sender, EventArgs e) { //this section create a string variable. string plant = "1 Carrot"; label1.Text = "string of plant : "; label1.Text += plant; //split string and create an array of two elements. string[] array = plant.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); //create a new dictionary object. Dictionary<int, string> dictionary = new Dictionary<int, string>(); //create and populate a new keyvaluepair from splitted string. KeyValuePair<int, string> pair = new KeyValuePair<int, string>(Convert.ToInt32(array[0]), array[1]); //dictionary add new keyvaluepair dictionary.Add(pair.Key, pair.Value); label1.Text += Environment.NewLine+"dictionary keys and values : "; foreach (KeyValuePair<int, string> p in dictionary) { label1.Text += p.Key + " ------- " + p.Value; } } |
Output: