欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#转换全角半角方法示例

程序员文章站 2024-02-22 20:39:22
c#全角转换成半角 新建一个项目quanbanjiao,在此项目下新建一个类class1 复制代码 代码如下:using system;using system.web...

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();
        }
    }
}