如何在c#中从文本框中拆分数字 [英] how to split number from textbox in c#

查看:160
本文介绍了如何在c#中从文本框中拆分数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


i有一个文本框,我的文本框中有一些数字像这样

Hi i 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

推荐答案

使用 Linq [ ^ ]:



Using Linq[^]:

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


你可以用+5+代替*,用+2+和构建数学表达式,然后你可以使用数学表达式评估器库,如 http://ncalc.codeplex.com/ [ ^ ]评估最终结果。



或没有其他图书馆 [ ^ ]



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 [^]

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#中从文本框中拆分数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆