一聚教程网:一个值得你收藏的教程网站

热门教程

C# 判断字符串否为数字与字符串是否以数字开头

时间:2022-06-25 08:20:29 编辑:袖梨 来源:一聚教程网

判断字符串第一位是否为数字

 代码如下 复制代码

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 System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Regex regChina = new Regex( "^[^x00-xFF]");
Regex regNum = new Regex( "^[0-9]");
Regex regChar = new Regex( "^[a-z]");
Regex regDChar = new Regex( "^[A-Z]");
string str = "YL闫磊";
if (regNum.IsMatch(str))
{
MessageBox.Show( "是数字");
}
else if (regChina.IsMatch(str))
{
MessageBox.Show( "是中文");
}
else if (regChar.IsMatch(str))
{
MessageBox.Show( "小写");
}
else if (regDChar.IsMatch(str))
{
MessageBox.Show( "大写");
}
}
}
}

判断字符串是否为数字字符串

【方法一】:使用 try{} catch{} 语句。
      我们可以在try语句块中试图将string类型的字符串变量转换为int类型,如果该字符串不是数字字符串则会抛出异常,这时在catch语句块中就能捕获异常。一旦发现异常,则不是数字字符串。
我们可以以下三种方式将string类型转换为int类型。
(1)  int.Parse(string);
(2)  Convert.ToInt16(string);  //当数字字符串的位数大于4的时候请使用Convert.ToInt32()
(3)  Convert.ToInt32(string);

添加一个文本框TextBox1,和一个按钮Button1,当点击按钮时,判断文本框中的内容是否为数字字符串,是的话则输出转换后的数值。

 

 代码如下 复制代码
protected void Button1_Click(object sender, EventArgs e)
{
        string message = TextBox1.Text.Trim();
        int result;
        if(isNumberic(message,out result))
        {
            string tt="";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", tt);
        }
        else
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "");
}
protected bool isNumberic(string message,out int result)
{
       //判断是否为整数字符串
       //是的话则将其转换为数字并将其设为out类型的输出值、返回true, 否则为false
        result = -1;   //result 定义为out 用来输出值
        try
        {
          //当数字字符串的为是少于4时,以下三种都可以转换,任选一种
          //如果位数超过4的话,请选用Convert.ToInt32() 和int.Parse()
 
          //result = int.Parse(message);
          //result = Convert.ToInt16(message);
            result = Convert.ToInt32(message);    
            return true;
        }
        catch
        {
            return false;
        }
}

热门栏目