Rizwan ali Rizwan ali - 7 days ago 6
C# Question

How to parse this following string?

I have to parse this string

"Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing"


as Code, Description like Code=Cust and Description=Customer

split on basis of space is not working for this because there is also a space in description too .

Answer

Instead of splitting on space you can split on the equals sign. Then the code will be the value after the last space of the previous item and the description will be everything up to the last space making sure to trim the spaces that might show up before the equals. And you can replace the Dictionary with whatever data type you want to load the values into. Also you have to handle the first and last values as special cases. Note this will only work if the codes do not contain spaces.

string str = "Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing";

var separated = str.Split('=');

string code = separated[0].Trim();
var codeAndDescription = new Dictionary<string, string>();
for (int i = 1; i < separated.Length - 1; i++)
{
    int lastSpace = separated[i].Trim().LastIndexOf(' ');
    var description = separated[i].Substring(0, lastSpace).Trim();
    codeAndDescription.Add(code, description);
    code = separated[i].Substring(lastSpace + 1).Trim();
}

codeAndDescription.Add(code, separated[separated.Length - 1]);

foreach (var kvp in codeAndDescription)
    Console.WriteLine(kvp);

Outputs

[Cust, Customer]

[CustCR, Customer Credit]

[Prod, Product]

[SalesRep, Sales Rep]

[TaxCat, Tax Category]

[TaxId, Tax ID]

[VolBill, Volume Billing]