jhonny625 jhonny625 - 1 month ago 7
C# Question

Evalute (sum) multiple string delimited in csharp?

How i can evaluate this string with this delimiter #c"stringtosum"#g

code1,code2,#c55+35+97#g,coden,code3,code4,#c44+25+07#gcoden

55+35+97=187

44+25+07=76

and output this

code1,code2,#c187#g,coden,code3,code4,#c76#gcoden

i am using this two string ,#c55+35+97#g ,#c44+25+07#g ,, im tring to evaluate (sum) this two

55+35+97=187

44+25+07=76

and output this

code1,code2,#c187#g,coden,code3,code4,#c76#gcoden

i have multiple string to sum

please help me

Answer

First you can use a regular expression like #c([^#]*)# to find the matches. Then you just need to take the string in the grouping, split on the plus sign, parse the values to integers, and do the sum, like this.

string input = "code1,code2,#c55+35+97#g,coden,code3,code4,#c44+25+07#gcoden";

string output = Regex.Replace(
    input, 
    "#c([^#]*)#", 
    m => "#c" + m.Groups[1].Value.Split('+').Sum(int.Parse) + "#");

Console.WriteLine(output);

Outputs

code1,code2,#c187#g,coden,code3,code4,#c76#gcoden

Comments