日期:2014-05-18  浏览次数:20842 次

用c#怎么判断输入的是数字还是字符串
比如
  string n = Console.ReadLine();
  if(?)
  {
  //执行数字的程序
  }
  else
  {
  //执行字符串的程序
  }

------解决方案--------------------
public static bool IsNumeric(string value)
{
return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
}
tring n = Console.ReadLine();
int num;
if (IsNumeric(n))
{
//执行数字的程序
}
else
{
//执行字符串的程序
}
------解决方案--------------------
C# code

bool isNum = false;
double num = 0;
try
{
    num = double.Parse(n);
    isNum = true;
}
catch
{

}
if(isNum)
{
    // do somthing with num
}
else
{
    // do something with n
}

------解决方案--------------------
探讨
引用:
public static bool IsNumeric(string value)
{
return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
}
tring n = Console.ReadLine();
int num;
if (IsNumeric(n))
{
//执行数字的程序
}
else
{
……