本文介绍了如何在c#中从文本框中拆分数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
i有一个文本框,我的文本框中有一些数字像这样
Hii have a text box and i have some numbers in my text box like this
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,
现在我想把它们拆分成这样的
有*的数字,我想逐个计算这些数字+5并且,一个接一个地+2并将它们写在另一个文本框中
这是我的代码
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
foreach (var c in richTextBox6.Text)
{
string a = c.ToString();
string[] b = a.Split('*');
richTextBox7.Text += b[a.Length - 1];
}
但它只是spli*和,
如何逐个计算这些数字?
尊重
but it just spli "*" and ","
how calculate those numbers one by one?
With Respect
推荐答案
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
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"]);
}
这篇关于如何在c#中从文本框中拆分数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!