如何确定输入是字符串还是整数 [英] how to determine whether input is string or int

查看:180
本文介绍了如何确定输入是字符串还是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我正在使用Visual Studio 2008
我有一个带有两个In Put文本框的表单
我想检查输入是否为int类型,如果是,则将值加总,否则,我将两个值(如果它们为字符串类型)连接起来

我该如何实现?
在此先感谢
您忠实的
Martin

Hi there,

I am using visual studio 2008
I have a form with two In Put text Boxes
I want to check whether the inputs are of type int, if they are, i sum up the value else, i just concatenate the two values(if they are of string types)

How can i achieve this?
Thanks in Advance
Yours faithfully
Martin

推荐答案

有点奇怪的要求,但是我希望这只是为了培训.如果使用int.TryParse,则如果解析失败,它将返回false.实际上,这是验证字符串以解析为整数的唯一可靠方法.您可以使用任何整数类型来做到这一点.

—SA
A bit weird requirement, but I hope this is just for training. If you use int.TryParse, it will return false if parsing is unsuccessful. Practically, this is the only reliable way to validate the string for parsing into integer. You can do it with any of the integer types.

—SA


尝试这种方式:

Try this way:

void Add()
{
    int a, b;
    //Check for integer
    if (int.TryParse(textBox1.Text, out a) && int.TryParse(textBox2.Text, out b))
    {
        txtResult.Text = (a + b).ToString();
    }    
    // The value in textboxes are string
    else
    {
        txtResult.Text = textBox1.Text + textBox2.Text
    }
}



希望对您有所帮助.



Hope this helps.


将两个参数都当作字符串输入:
Take in both parameters as strings:
txtResult.Text = HandleInput(textbox1.Text, textbox2.Text);

public string HandleInput(string s1, string s2)
{
int i1;
int i2;
if (int.TryParse(s1, out i1) && int.TryParse(s2, out int2))
return (i1 + i2).ToString();
else
return s1 + s2;
}


这篇关于如何确定输入是字符串还是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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