c#你怎么判断一个字符串是否是数字?

在C#中调用Microsoft.VisualBasic命名空间下的类型验证函数   VB.NET中还是有很多有用的东西的。比如VB.NET可以直接调用Microsoft.VisualBasic命名空间下的各种有用的函数,特别是一些类型验证函数(IsDate,IsNumeric)就十分有用。就拿判断是否为数字来说,在网上我找到了在C#中用到的三种方法(但都有各自的不足之处):1、将字符串分解成Char,然后用Char.IsNumber(c)验证public bool IsNum 阅读详情
今天在写代码时突然想起测试经常用Microsoft.VisualBasic.Information.IsNumeric判断 url参数是否为数字时的这个方法的效率
因为数字是字符串是直接使用的,所以不需要转型,也就没有用tryparse
结果一测试吓一跳,这个方法的效率是如此的低,再测试了下tryparse还不错,正则的也比较差,
没什么技术含量,看结果吧:

先拓展下字符串:

   public static class Common
    {
        //isDigit
        public static bool isNumberic1(this string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            foreach (char c in _string)
            {
                if (!char.IsDigit(c))//if(c<'0' || c>'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
                    return false;
            }
            return true;
        }

        //vb isnumberic
        public static bool isNumberic2(this string _string)
        {
            return !string.IsNullOrEmpty(_string) && Microsoft.VisualBasic.Information.IsNumeric(_string);
        }
        //try parse
        public static bool isNumberic3(this string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            int i = 0;
            return int.TryParse(_string, out i);
        }

        //try catch
        public static bool isNumberic4(this string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            try { int.Parse(_string); }
            catch { return false; }
            return true;
        }
        //regex
        public static bool isNumberic5(this string _string)
        {
            return !string.IsNullOrEmpty(_string) && Regex.IsMatch(_string, "^\\d+$");
        }
    }

测试的代码:

class Program
    {
        static void Main(string[] args)
        {

            Test("1234");
            Test("1234a");
            Test("a1234");
            Test("");
            Test(null);
            
        }

        static void Test(string str)
        {
            bool res1 = false, res2 = false, res3 = false, res4 = false, res5 = false;
            Stopwatch wat = new Stopwatch();
            wat.Start();//
            for (int i = 1; i < 100000; i++)
            {
                res1 = str.isNumberic1();
            }
            wat.Stop();
            Console.WriteLine("isDigit      {0}:{1},{2}", str, wat.ElapsedMilliseconds, res1);

            wat.Reset();
            wat.Start();
            for (int i = 1; i < 100000; i++)
            {
                res2= str.isNumberic2();
            }
            wat.Stop();
            Console.WriteLine("isNumberic   {0}:{1},{2}", str, wat.ElapsedMilliseconds, res2);

            wat.Reset();
            wat.Start();
            for (int i = 1; i < 100000; i++)
            {
                res3 = str.isNumberic3();
            }
            wat.Stop();
            Console.WriteLine("try parse    {0}:{1},{2}", str, wat.ElapsedMilliseconds, res3);

            wat.Reset();
            wat.Start();
            for (int i = 1; i < 100000; i++)
            {
                res4 = str.isNumberic4();
            }
            wat.Stop();
            Console.WriteLine("try catch    {0}:{1},{2}", str, wat.ElapsedMilliseconds, res4);

            wat.Reset();
            wat.Start();
            for (int i = 1; i < 100000; i++)
            {
                res5 = str.isNumberic5();
            }
            wat.Stop();
            Console.WriteLine("regex        {0}:{1},{2}", str, wat.ElapsedMilliseconds, res5);
            Console.WriteLine();
        }
    }

下面是我本机的测试结果

isDigit      1234:5,True
isNumberic   1234:166,True
try parse    1234:21,True
try catch    1234:22,True
regex        1234:134,True

isDigit      1234a:5,False
isNumberic   1234a:196,False
try parse    1234a:19,False
try catch    1234a:5182,False
regex        1234a:150,False

isDigit      a1234:2,False
isNumberic   a1234:184,False
try parse    a1234:16,False
try catch    a1234:5084,False
regex        a1234:106,False

isDigit      :1,False
isNumberic   :0,False
try parse    :0,False
try catch    :1,False
regex        :0,False

isDigit      :1,False
isNumberic   :0,False
try parse    :1,False
try catch    :1,False
regex        :0,False

结果:循环判断是否是数字字符效率是最高的
而VisualBasic的方法效率比较低了
顺便测试了下VisualBasic里的left和right方法效率也一样的低,还不及substring的十分之一
所以VisualBasic里虽然有几个方法从名字看来比较好用,实际却比较杯具。


转载请注明出处:http://www.cnblogs.com/sohighthesky/ 



C#判断字符串是否为数字字符串 C#判断字符串是否为数字字符串 在进行C#编程时候,有的时候我们需要判断一个字符串是否是数字字符串,我们可以通过以下两种方法来实现。 【方法一】:使用 try{} catch{} 语句。 我们可以在try语句块中试图将string类型的字符串变量转换为int类型,如果该字符串不是数字字符串则会抛出异常,这时在catch语句块中就能捕获异常。一旦发现异常,则不是数字字符串。 我们可以以下三种方式将s... 阅读详情

相关推荐

C#中三种判断是不是数字的方法

C#中三种判断是不是数字的方法: 第一种: try catch方法。。。 第二种: 正则表达式方法。。。 第三种: Double.TryParse方法。。。 具体见文档

c# 判断输入的字符串是否是数字的几种方法

//第一种 用正则 有空格也是返回false static string Regn(string input) { Regex reg = new Regex("^[1-9]\\d*$"); return reg.Match(input).Value ;//返回值可以是bool,可以用isMatch. } //...

ayman_zawahiri的博客 1万+

VASP能带计算避坑指南:从CHGCAR读取失败到成功解决的全过程

本文深度解析VASP能带计算中常见的“CHGCAR读取失败”报错,并提供从静态自洽到非自洽计算的全流程避坑指南。核心解决方案包括使用CONTCAR替代POSCAR、调整SYMPREC参数以处理对称性判定问题,并推荐利用vaspkit工具自动化生成输入文件,确保计算流程稳健高效。

weixin_29245767的博客 772

C# 判定字符串是否为数字的方法

该方法只有当字符串是数字的时候,才能将字符串转换为数字并且返回结果true,否则将字符串转换为0并且返回结果false。此方法特别适用于字符串不是数字,防止转换过程中出现异常的情况,如果字符串不是数字,方法默认返回0。

淳潜 的博客 5376

从仿真到现实:BeamDojo双足机器人项目实战指南(附完整配置清单)

本文提供了一份基于BeamDojo项目的双足机器人从仿真训练到现实部署的完整实战指南。详细拆解了硬件选型(如宇树G1、Jetson Orin NX、Livox Mid-360)、Isaac Gym仿真环境搭建、强化学习训练技巧(如双评论家架构、课程学习)以及关键的Sim2Real迁移策略,旨在帮助开发者将前沿研究成果转化为可落地的工程实践。

hhh00的博客 877

Python 逆向解析知乎盐选反爬字体,实现内容精准还原

本文详细解析了知乎盐选内容的反爬字体机制,并提供了使用Python逆向解析WOFF字体文件的完整方案。通过fontTools库构建解码字典,实现乱码文本的精准还原,帮助开发者应对动态字体策略,同时强调法律与道德风险。

weixin_29268385的博客 1297

C#判断字符串中的内容是否为纯数字,最细教程

它通过将指定的字符串转换为等效的有符号整数表示并返回true。如果转换成功, true;这可以使用Regex.IsMatch()方法,它确定指定的字符串是否与提供的正则表达式匹配。Char.IsDigit()方法返回一个布尔值,用来指明指定的字符是否为数字。

i78i845的博客 8017

ANSYS MAXWELL内置式永磁同步电机(IPMSM)转矩最大时输入电流相位的确定

1.在转子转速为零时看一个周期内的转矩变化

qq_41752507的博客 6517

C# 判断一个字符串是否数字开头

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;   using

longxinzishu的专栏 2486

从零构建工业级SPI-CAN网关:CH347与CH9431的软硬件协同设计实战

本文详细介绍了基于CH347和CH9431芯片构建工业级SPI-CAN网关的完整方案。通过硬件架构设计、Linux驱动定制、并发处理优化和EMC抗干扰测试,实现高可靠性通信网关,适用于工业自动化和汽车电子等严苛环境。

spark7igniter的博客 632

PyQt5 + HFSS:给你的仿真脚本做个专属GUI界面(零基础搭建指南)

本文详细介绍了如何使用PyQt5为HFSS仿真脚本创建专属GUI界面,适合零基础用户快速上手。通过Python二次开发,实现参数可视化调整、进度实时监控等功能,大幅提升团队协作效率。文章涵盖环境配置、界面设计、HFSS集成到打包部署的全流程,是仿真工程师提升工作效率的实用指南。

weixin_42535720的博客 185

C#判断一个字符串是否是数字或者含有某个数字

第一种就是 最常见的 用Try..Catch.. 再try中强转你要确认的string 类型 成功就是int catch 就不是 string a = "avdfd"; try { int b = int.Parse(a); } ...

1360

OpenClaw部署太难?汉化版+中文社区+国产替代品,国内用户零门槛指南

OpenClaw作为GitHub 10万+星的开源AI助手平台,近期在国内AI圈备受关注 🌟 但部署难度和英文界面让很多用户望而却步。本文整理了针对国内用户的友好资源和简便替代方案,帮助国内用户零门槛上手AI助手工具 🚀

XiaoqiangClub的博客 5758

c# 如何判断一个字符串是一个数字

  最好的办法是使用正则表达式   using   System.Text.RegularExpressions;     ....     Regex   myRex   =   new   Regex("^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?$");     String   s   =   "123.345";             Mat

daming_ocean的专栏 1303

YOLOv8改进 | Conv篇 | 利用YOLOv9的GELAN模块替换C2f结构(附轻量化版本 + 高效涨点版本 + 结构图)

本文给大家带来的改进机制是利用2024/02/21号最新发布的YOLOv9其中提出的GELAN模块来改进YOLOv8中的C2f,GELAN融合了CSPNet和ELAN机制同时其中利用到了RepConv在获取更多有效特征的同时在推理时专用单分支结构从而不影响推理速度,同时本文的内容提供了两种版本一种是参数量更低涨点效果略微弱一些的版本(参数量V8n下降80w,计算量为6.1GFLOPs),另一种是参数量稍多一些但是效果要不参数量低的效果要好一些(均为我个人整理),提供两种版本是为了适配不同需求的读者,具体选择

Snu77的博客 7567

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

C#如何判断一个字符串中是否有非英文、数字字符

using System.Text.RegularExpressions; Regex rex = new Regex("[a-z0-9A-Z_]+"); Match ma = rex.Match(“你的复字符制串zhidao”); if (ma.Success) { MessageBox.Show(“OK”); } else { MessageBox.Show(“Fail”); }

IT技术猿猴的博客 2394

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

C# 判断一个字符串是否为数字

判断一个字符串是否为数字 String num1=“200.98”; int num2; double num3; if (int.TryParse(num1, out num2)) return"都是数字,并且是整数"; if (double.TryParse(num1, out num3)) return"都是数字,并且是浮点数"; else return"不是数字"; ...

Pei_hua100的专栏 801

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C# 判断一个字符串是否都是数字

using   System;      using   System.Text.RegularExpressions;          public    bool   IsNumber(String    strNumber)      {      Regex    objNotNumberPattern=new   Regex("[^0-9.-]"

minyangchina的专栏 678

【转】C#判断一个字符串是否是数字

//判断一个string是否可以为数字 //方案一:Try...Catch(执行效率不高) /// /// 名称:IsNumberic /// 功能:判断输入的是否是数字 /// 参数:string oText:源文本 /// 返回值: bool true:是 false:否

拓 1224

C#中,判断一个字符串是否为数字

用正则进行验证。 需要引用 using System.Text.RegularExpressions; 事件里这么写。 bool yz=Regex.IsMatch(TextBox1, @"^[0-9]*[1-9][0-9]*$"); if(!yz) { MessageBox.Show("必须是正整数"); } ...

weixin_34288121的博客 176

c#你怎么判断一个字符串是否是数字?(转)

今天在写代码时突然想起测试经常用Microsoft.VisualBasic.Information.IsNumeric判断 url参数是否为数字时的这个方法的效率因为数字是字符串是直接使用的,所以不需要转型,也就没有用tryparse结果一测试吓一跳,这个方法的效率是如此的低,再测试了下tryparse还不错,正则的也比较差,没什么技术含量,看结果吧:先拓展下字符串:code pub...

weixin_30312563的博客 91

判断一个字符串是否全是数字的多种方法及其性能比较(C#实现)

在编程的时候,经常遇到要判断一个字符串中的字符是否全部是数字(0-9),本来是一个很容易实现的功能,但程序员首先会想到的是,这样简单的功能有没有现成的函数可以用呢?VB.NET中有个IsNumeric(object),C#中只有判断单个字符的Char.IsNumber(),IsNumeric可以判断double类型的数字字符串,但无法排除正负号和小数点,如果判断字符串是否是一个数的话用它挺合适,但

⒈oo﹪緈鍢 905

判断一个字符串是否全是数字的多种方法及其性能比较(C#实现)

    在编程的时候,经常遇到要判断一个字符串中的字符是否全部是数字(0-9),本来是一个很容易实现的功能,但程序员首先会想到的是,这样简单的功能有没有现成的函数可以用呢?VB.NET中有个IsNumeric(object),C#中只有判断单个字符的Char.IsNumber(),IsNumeric可以判断double类型的数字字符串,但无法排除正负号和小数点,如果判断字符串是否是一个数的话用它挺

fanruinet的专栏 1万+
上一篇: C# 登录QQ网站并获取QQ相关信息
下一篇: C# 一个关于等差数列的算法
Hauk
博客等级 码龄15年 219粉丝 20原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值