检查字符串是否包含数值

本文关键字:包含数 是否 字符串 检查 | 更新日期: 2023-09-27 18:32:24

我正在尝试检查字符串是否包含数值,如果它没有返回标签,那么我想显示主窗口。如何做到这一点?

If (mystring = a numeric value)
            //do this:
            var newWindow = new MainWindow();
            newWindow.Show();
If (mystring = non numeric)
            //display mystring in a label
            label1.Text = mystring;
else return error to message box

检查字符串是否包含数值

使用TryParse。

double val;
if (double.TryParse(mystring, out val)) {
    ..
} else { 
    ..
}

这将适用于直接转换为数字的字符串。如果你还需要担心像 $ 和 这样的东西,那么你需要先做更多的工作来清理它。

Int32 intValue;
if (Int32.TryParse(mystring, out intValue)){
  // mystring is an integer
}

或者,如果是十进制数:

Double dblValue;
if (Double.TryParse(mystring, out dblValue)){
  // mystring has a decimal number
}

一些例子,顺便说一句,可以在这里找到。

Testing foo:
Testing 123:
    It's an integer! (123)
    It's a decimal! (123.00)
Testing 1.23:
    It's a decimal! (1.23)
Testing $1.23:
    It's a decimal! (1.23)
Testing 1,234:
    It's a decimal! (1234.00)
Testing 1,234.56:
    It's a decimal! (1234.56)

我测试过的还有几个:

Testing $ 1,234:                      // Note that the space makes it fail
Testing $1,234:
    It's a decimal! (1234.00)
Testing $1,234.56:
    It's a decimal! (1234.56)
Testing -1,234:
    It's a decimal! (-1234.00)
Testing -123:
    It's an integer! (-123)
    It's a decimal! (-123.00)
Testing $-1,234:                     // negative currency also fails
Testing $-1,234.56:
double value;
if (double.tryParse(mystring, out value))
{
        var newWindow = new MainWindow();
        newWindow.Show();
}
else
{
    label1.Text = mystring;
}
您可以

简单地引用Microsoft.VisualBasic.dll,然后执行以下操作:

if (Microsoft.VisualBasic.Information.IsNumeric(mystring))
{
    var newWindow = new MainWindow();
    newWindow.Show();
}
else
{
    label1.Text = mystring;
}

VB 实际上性能更好,因为它不会为每个失败的转换抛出异常。

请参见: 探索 C# 的 IsNumeric

您可以使用布尔值来判断字符串是否包含数字字符。

public bool GetNumberFromStr(string str)
    {
        string ss = "";
        foreach (char s in str)
        {
            int a = 0;
            if (int.TryParse(Convert.ToString(s), out a))
                ss += a;
        }
        if ss.Length >0
           return true;
        else
           return false;
    } 

尝试将标签的标题放入字符串中,然后使用Int.TryParse()方法确定文本是整数还是字符串。如果是,该方法将返回 true,否则它将返回 false。代码将如下所示:

if (Int.TryParse(<string> , out Num) == True)
{
   // is numeric
}
else
{
   //is string
}   

其中,如果转换成功,则 Num 将包含您的整数值

可以在

以下位置找到执行此操作的方法的一个很好的例子: http://msdn.microsoft.com/en-us/library/f02979c7.aspx

甚至还有一些代码几乎完全按照你想要的方式做一些事情。 如果你需要整数值,可以使用 Int32.TryParse(string)。 如果您预计会出现双精度,请使用 Double.TryParse(string)。