字串是否为某个类型的数值

有时候需要判断一个字串是不是一个int/double/float.
C#没有直接的方法实现,可以自己用如下几个方法实现:
<1>try-catch

class Program
{
public static bool IsInt32(string s)
{
try
{
int n = Int32.Parse(s);
return true;
}
catch
{
return false;
}
}
static void Main(string[] args)
{
string str = "123456789101112";
Console.WriteLine("{0}!", str = (IsInt32(str) ? "Yes":"No"));
}
}


<2>正则表达式

using System.Text.RegularExpressions;
class Program
{

static void Main(string[] args)
{
string str = "12345678910111a2222";
Regex rex = new Regex(@"^\d+\d$");
Console.WriteLine("{0}!", str = (rex.IsMatch(str) ? "Yes" : "No"));
}
}


效率比较

class Program
{
static int times = 10000000;

public static bool TryCatch(string s)
{
try
{
int n = Int32.Parse(s);
return true;
}
catch
{
return false;
}
}
public static bool IsNumber(string s)
{
foreach (char c in s)
{
if (c < '0' || c > '9')
return false;
}
return true;
}


static void Main(string[] args)
{

string str = "1234567891";
int rx, tc, isn;
Regex rex = new Regex(@"^\d+\d$");
int counter;

counter = System.Environment.TickCount;
for (int i = 0; i < times; i++)
{
IsNumber(str);
}
counter = System.Environment.TickCount - counter;
isn = counter;
Console.WriteLine("InNumber time:{0}ms!", isn);

counter = System.Environment.TickCount;
for (int i = 0; i < times; i++)
{
rex.IsMatch(str);
}
counter = System.Environment.TickCount - counter;
rx = counter;
Console.WriteLine("Regex time:{0}ms!", rx);

counter = System.Environment.TickCount;
for (int i = 0; i < times; i++)
{
TryCatch(str);
}
counter = System.Environment.TickCount - counter;
tc = counter;
Console.WriteLine("TryCatch time:{0}ms!", tc);

Console.WriteLine("InNumber:Regex:TryCatch = {0} : {1} : {2}",tc/isn, tc/rx, tc/tc);
//Console.WriteLine("InNumber:TryCatch:Regex = {0} : {1} : {2}",rx/isn, rx/tc, rx/rx);
}

可以发现,trycatch 在有没有抛出异常的情况下,差别很大。
要是有异常,那么IsNumber :Regex : trycatch = 446 : 68 : 1
要没有异常,那么IsNumber : trycatch :Regex = 7 : 4 : 1
但无论如何,自己写的函数始终是最快的。

你可能感兴趣的:(正则表达式,C,C++,C#)