Himaan Singh Himaan Singh - 3 months ago 10
C# Question

Extract substrings from a string

I have string variable that has value like this

string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";


As i am extracting from XML so Endpoint , Intervene , Mask and Purpose remains
same but its value can change.
I want to store these Endpoint , intervene , mask and purpose separately in different variables any help will be much appreciated.

Answer

Split your string first by , and then by : and save the result in dictionary:

public class Program
{
    public static void Main(string[] args)
    {
        string hello = "Endpoint: Efficacy, Intervene: Single Group, Mask: Open, Purpose: Treatment";
        string[] arr = hello.Split(',');
        Dictionary<string, string> result = new Dictionary<string, string>();
        foreach(string s in arr)
        {
            string[] keyValuePair = s.Split(':');
            result[keyValuePair[0].Replace(" ","")] = keyValuePair[1].Replace(" ","");

        }

        foreach(var v in result)
        {
            Console.WriteLine(v.Key + " : " + v.Value );
        }


    }
}