簡體   English   中英

檢查字符串是否包含數值

[英]check if a string contains a numeric value

我試圖檢查字符串是否包含數字值,如果它沒有返回標簽,如果它然后我想顯示主窗口。 如何才能做到這一點?

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
}

一些例子,BTW,可以在這里找到

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;
    } 

嘗試將Label的標題轉換為字符串,並使用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(字符串)。 如果您預期雙打,請使用Double.TryParse(string)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM