判断C#中的字符串是否是数字,如果是转换成int类型
1.通过正则表达式(可以判断正数和负数)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;
}
{
int i;
if(str != null && System.Text.RegularExpressions.Regex.IsMatch(str,@"^-?\d+$"))
i = int.Parse(str);
else
i = -1;
return i;
}
2.通过字符
/// <summary>
/// 判断是否是数字
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private bool IsNumeric(string number)
{
try
{
for(int i=0;i<number.Length;i++)
{
if(number<'0'||number>'9')
{
return false;
}
}
return true;
}
catch
{
return false;
}
}
/// 判断是否是数字
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private bool IsNumeric(string number)
{
try
{
for(int i=0;i<number.Length;i++)
{
if(number<'0'||number>'9')
{
return false;
}
}
return true;
}
catch
{
return false;
}
}
3.通过char.IsNumber方法
/// 判断是否是数字
/// </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;
}
}
/// </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,catch
/// 判断是否是数字
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private bool IsNumeric(string number)
{
try
{
int.Parse(number);
return true;
}
catch
{
return false;
}
}
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private bool IsNumeric(string number)
{
try
{
int.Parse(number);
return true;
}
catch
{
return false;
}
}