如何在文本框中拆分字符串并添加值? [英] How do I split a string in a textbox and add the values?
本文介绍了如何在文本框中拆分字符串并添加值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void calctxt_KeyDown(object sender, KeyEventArgs e)
{
double Total;
string[] numbers = calctxt.Text.Split('+');
Total = 0;
foreach(string value in numbers)
{
Total = Total + numbers(num)
}
如何填写此字符串以添加+符号之间的所有数字?
我有什么试过:
How would I complete this string to add all the numbers between the + signs?
What I have tried:
private void calctxt_KeyDown(object sender, KeyEventArgs e)
{
double Total;
string[] numbers = calctxt.Text.Split('+');
Total = 0;
foreach(string value in numbers)
{
Total = Total + numbers(num)
}
我如何填写此字符串以添加+符号之间的所有数字?
How would I complete this string to add all the numbers between the + signs?
推荐答案
尝试这样的事情:
Try something like this:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(Compute());
}
private static string Compute(){
string message = string.Empty;
bool isValid = true;
double result = 0;
string sampleText = "2+5+1+6+3+2+1";
string delimtedValue = "+";
if(sampleText.Contains(delimtedValue)){
string[] numbers = sampleText.Split(delimtedValue.ToCharArray());
double val;
foreach(string num in numbers)
{
if (!double.TryParse(num, out val))
{
message ="Unable to compute. String has invalid numeric values";
isValid = false;
break;
}
result = result + val;
}
}
if(!isValid)
return message;
else
return string.Format("The total sum is: {0}", result);
}
}
您需要使用 double.TryParse [ ^ ]
You need to convert the strings to numbers inside your loop, using double.TryParse[^]
double val;
if (!double.TryParse(value, out val))
{
... report problem to user ...
return;
}
然后你可以将它们添加到你的总数中。
You can then add them into your total.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
double Total;
string[] numbers = textBox1.Text.Split('+');
Total = 0;
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
Total = Total + Convert.ToDouble(value);
}
}
textBox2.Text = Total.ToString();
}
这篇关于如何在文本框中拆分字符串并添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文