Judge whether the string in C # Is a number. If it is converted to the int type
1. Use a regular expression (positive and negative values can be determined)
Public int isnumeric (string Str)
{
Int I;
If (STR! = NULL & system. Text. regularexpressions. RegEx. ismatch (STR, @ "^ -? \ D + $ "))
I = int. parse (STR );
Else
I =-1;
Return I;
}
2. Pass characters
/// <Summary>
/// Determine whether it is a number
/// </Summary>
/// <Param name = "Number"> </param>
/// <Returns> </returns>
Private bool isnumeric (string number)
{
Try
{
For (INT I = 0; I <number. length; I ++)
{
If (number [I] <'0' | Number [I]> '9 ')
{
Return false;
}
}
Return true;
}
Catch
{
Return false;
}
}
3. Use the char. isnumber Method
/// Determine whether it is a number
/// </Summary>
/// <Param name = "Number"> </param>
/// <Returns> </returns>
Private bool isnumeric (string number)
{
Try
{
For (INT I = 0; I <number. length; I ++)
{
If (! Char. isnumber (number, I ))
{
Return false;
}
}
Return true;
}
Catch
{
Return false;
}
}
4. Try and catch
/// Determine whether it is a number
/// </Summary>
/// <Param name = "Number"> </param>
/// <Returns> </returns>
Private bool isnumeric (string number)
{
Try
{
Int. parse (number );
Return true;
}
Catch
{
Return false;
}
}