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

有时候需要判断一个字串是不是一个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
但无论如何,自己写的函数始终是最快的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值