Home > Software design >  How to split string based on multiple Keywords in c#?
How to split string based on multiple Keywords in c#?

Time:10-19

I have a string which has string values separated by special character ';' and I need to split string and store each value in separate string. In my ipStr, keywords like ServerName, DBName, TableNames and ColumnNames are identifiers and it will not change only the values might get changed.

For Example.

string ipStr = "ServerName=DevTestServer;DBName=CustomerSummary;TableNames=CustomerDetails&OrderDetails;ColumnNames=ID,CustName,OrderID;"

Now I want to split ServerName, DBName, TableNames and ColumnNames values separately and store each value in in different strings. I tried below but after finding ServerName, identifying DBName part looks difficult and also it does not look like a proper way of coding.

string ServerIdentifier = "ServerName=";
string separator = ";";
string serverName = ipStr.Substring(ipStr.IndexOf(ServerIdentifier), ipStr.IndexOf(delimiter));

What is the easiest way of getting values like below from the ipStr.

string ServerName="DevTestServer";
string DBName="CustomerSummary";
string TableNames="CustomerDetails&OrderDetails";
string ColumnNames="ID,CustName,OrderID";

CodePudding user response:

SqlConnectionStringBuilder wont work because ServerName etc isn't a valid token in a connection string

However, a low tech approach is to use a good old fashioned Split and ToDictionary

var someWeirdStr = "ServerName=DevTestServer;DBName=CustomerSummary;TableNames=CustomerDetails&OrderDetails;ColumnNames=ID,CustName,OrderID;";

var results = someWeirdStr
   .Split(';',StringSplitOptions.RemoveEmptyEntries)
   .Select(x => x.Split('='))
   .ToDictionary(x => x[0], x => x.ElementAtOrDefault(1));

Console.WriteLine(results["ServerName"]);
Console.WriteLine(results["DBName"]);
Console.WriteLine(results["TableNames"]);
Console.WriteLine(results["ColumnNames"]);

Output

DevTestServer
CustomerSummary
CustomerDetails&OrderDetails
ID,CustName,OrderID

CodePudding user response:

you need to split the string by semi colon and then remove any empty strings then, after that you can split again by equals and create a dictionary of the results.

string ipStr = "ServerName=DevTestServer;DBName=CustomerSummary;TableNames=CustomerDetails&OrderDetails;ColumnNames=ID,CustName,OrderID;";
    
    var values = ipStr.Split(';')
        .Where(x => !string.IsNullOrEmpty(x))
        .Select(x => {
            var pair = x.Split('=');
            return KeyValuePair.Create<string, string>(pair[0], pair[1]);
        })
        .ToDictionary(pair => pair.Key, pair => pair.Value);
    foreach (var i in values) {
        Console.WriteLine($"{i.Key}: {i.Value}");
    }
  • Related