C#输入全角转半角以及格式检查

新建一个项目quanbanjiao,在此项目下新建一个类Class1

using System;
using System.Web;
using System.Text;

namespace quanbanjiao
{
    public class Class1
    {
        /**/
        /// <summary>
        /// 判断字符是否英文半角字符或标点
        /// </summary>
        /// <remarks>
        /// 32    空格
        /// 33-47    标点
        /// 48-57    0~9
        /// 58-64    标点
        /// 65-90    A~Z
        /// 91-96    标点
        /// 97-122    a~z
        /// 123-126  标点
        /// </remarks>
        public static bool IsBjChar(char c)
        {
            int i = (int)c;
            return i >= 32 && i <= 126;
        }

        /**/
        /// <summary>
        /// 判断字符是否全角字符或标点
        /// </summary>
        /// <remarks>
        /// <para>全角字符 - 65248 = 半角字符</para>
        /// <para>全角空格例外</para>
        /// </remarks>
        public static bool IsQjChar(char c)
        {
            if (c == '\u3000') return true;

            int i = (int)c - 65248;
            if (i < 32) return false;
            return IsBjChar((char)i);
        }

        /**/
        /// <summary>
        /// 将字符串中的全角字符转换为半角
        /// </summary>
        public static string ToBj(string type,string s)
        {
            if (s == null || s.Trim() == string.Empty) return s;

            StringBuilder sb = new StringBuilder(s.Length);
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] == '\u3000')
                    sb.Append('\u0020');
                else if (IsQjChar(s[i]))
                    sb.Append((char)((int)s[i] - 65248));
                else
                    sb.Append(s[i]);
            }

            //如果是int类型的,则只能输入int类型,否则自动设为0

            if (type.ToLower() == "int")
            {
                try
                {
                    Convert.ToInt32(sb.ToString());
                }
                catch
                {
                    return "0";
                }

            }

 

            //如果是float或double类型的,则只能输入这两种类型,否则自动设为0
            if (type.ToLower() == "float" || type.ToLower() == "double")
            {
                try
                {
                    Convert.ToDouble(sb.ToString());
                }
                catch
                {
                    return "0";
                }
            }
            return sb.ToString();
        }
    }
}

 

测试的例子:

using System;
using System.Web;
using quanbanjiao;//项目名称为quanbanjiao

namespace quanbanjiao
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.Text = Class1.ToBj("string", TextBox1.Text.Trim());
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值