Click here to Skip to main content
15,909,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have a text box and i have some numbers in my text box like this
C#
4*4*4*4*4*4*4*4*4*7*4*4*4*7*4*4*4*4*7*4*10*4*4*4*7*4*10*13*0,0,4,0,4,3,0,4,3,0,0,4,3,0,4,0,4,3,0,4,0,0,4,3,0,4,0,4,0,4,3,0,4,0,4,4,0,4,3,0,4,0,4,4,-1,

now i want to split them like this
number which has "*", i want to calculate one by one of those number + 5 and "," one by one +2 and write them in another textbox
and this is my code
C#
foreach (var c in richTextBox6.Text)
{
    string a = c.ToString();
    string[] b = a.Split('*');
    richTextBox7.Text += b[a.Length - 1];
}

but it just spli "*" and ","
how calculate those numbers one by one?
With Respect
Posted
Comments
Maciej Los 7-Apr-15 14:42pm    
What you mean: "i want to calculate one by one of those number + 5"? Do you mean add operation?
Avenger1 7-Apr-15 14:48pm    
the number has "*" +5 like this
4+5
13+5
7+5
4+5
.
.
.
Maciej Los 7-Apr-15 14:55pm    
Not clear... As far as i see you want to get sum of (number+5) when separator is *, and sum of (number+2) when separator is ,. Am i right? PLease, use "Reply" widget.

Using Linq[^]:

C#
string s = RichTextBox6.Text;
//in this example: 4*4*4*4*4*4*4*4*4*7*4*4*4*7*4*4*4*4*7*4*10*4*4*4*7*4*10*13*0,0,4,0,4,3,0,4,3,0,0,4,3,0,4,0,4,3,0,4,0,0,4,3,0,4,0,4,0,4,3,0,4,0,4,4,0,4,3,0,4,0,4,4,-1,
var addAndFive = s.Split(',')[0].Split('*').Sum(x=>Convert.ToInt32(x)+5);
//returns: 290
var addAndTwo = s.Split(',').Skip(1).Sum(x=>x == string.Empty ? 0 : Convert.ToInt32(x)+2);
//returns: 180
 
Share this answer
 
you can replace * with +5+ and , with +2+ and build math expression, then you can use mathematical expression evaluator library like http://ncalc.codeplex.com/[^] to evaluate final result.

or without other library [^]

C#
void Main()
{
	string input ="4*4,4,-4";
	input= input.Replace("*", "+5+");
	input =input.Replace(",", "+2+"); //4+5+4+2+4+2+-4
	var result = Evaluate(input); //17
}

double Evaluate(string expression)
{
	DataTable table = new DataTable();
	table.Columns.Add("expression", typeof(string), expression);
	DataRow row = table.NewRow();
	table.Rows.Add(row);
	return double.Parse((string)row["expression"]);
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900