C#中使用正则表达式实现汉字转拼音

目录

一、正则表达式基础 

二、实例

1.程序入口Form1.cs

2.类库PinYin.cs

三、生成效果

四、实例中的知识点 

1.Regex

2.ToCharArray()

3.IsMatch()

4.GetBytes()


一、正则表达式基础 

        在C#中使用正则表达式,首先要创建正则表达式对象,正则表达式对象的构造方法中接收一个正则表达式字符串,对象创建后,可以调用对象的IsMatch方法,对该方法中的字符串进行验证,如果验证成功将返回true,如果不成功则返回false。

        调用字符串对象的ToCharArray方法,可以根据当前的字符串对象中的字符内容,产生一个新的字符数组。字符串对象的ToCharArray方法:

//使用正则表达式
Regex reg =new Regex("^[\u4e00-\u9fa5]$"); //创建正则表达式对象
bool P_bl=reg.IsMatch("中");//调用IsMatch方法判断字符串中的字符是否为汉字
//字符串转字符数组
string str ="abc";
char[]mChar =str.ToCharArray();

        正则表达式经常用于数字或字符串等信息的验证及截取。

        适当地使用正则表达式,可以让字符串的处理变得更轻松。

二、实例

        使用正则表达式,可以方便地操作字符串,对字符串进行验证或提取。在本实例中,使用正则表达式验证字符串中的每一个字符是否为汉字,如果为汉字则查找汉字的拼音。

1.程序入口Form1.cs

//汉字转拼音
namespace _038
{
    public partial class Form1 : Form
    {
        private TextBox? textBox1;
        private TextBox? textBox2;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }

        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(12, 20),
                Name = "textBox1",
                Size = new Size(310, 23),
                TabIndex = 0
            };
            textBox1.TextChanged += TextBox1_TextChanged;
            // 
            // textBox2
            // 
            textBox2 = new TextBox
            {
                Location = new Point(12, 49),
                Name = "textBox2",
                Size = new Size(310, 23),
                TabIndex = 1
            };
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(334, 91);
            Controls.Add(textBox2);
            Controls.Add(textBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "汉字转拼音";
           
        }
        /// <summary>
        /// 调用拼音类的GetABC方法得到拼音字符串
        /// </summary>
        private void TextBox1_TextChanged(object? sender, EventArgs e)
        {
            textBox2!.Text = PinYin.GetABC(textBox1!.Text);
        }
    }
}

2.类库PinYin.cs

using System.Text;
using System.Text.RegularExpressions;

namespace _038
{
    internal partial class PinYin
    {
        /// <summary>
        /// 定义拼音区编码数组
        /// </summary>
        private static readonly int[] getValue =
                [
                -20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,
                -20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,
                -19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515,
                -19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249,
                -19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,
                -19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,
                -18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448,
                -18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,
                -17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,
                -17733,-17730,-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,
                -17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,-16915,-16733,
                -16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,-16452,-16448,
                -16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,
                -16212,-16205,-16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,
                -15933,-15920,-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667,-15661,-15659,
                -15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,-15408,-15394,
                -15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,
                -15149,-15144,-15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,
                -14941,-14937,-14933,-14930,-14929,-14928,-14926,-14922,-14921,-14914,-14908,-14902,
                -14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,-14663,-14654,
                -14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,
                -14170,-14159,-14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,
                -14109,-14099,-14097,-14094,-14092,-14090,-14087,-14083,-13917,-13914,-13910,-13907,
                -13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,-13611,-13601,
                -13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,
                -13340,-13329,-13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,
                -13068,-13063,-13060,-12888,-12875,-12871,-12860,-12858,-12852,-12849,-12838,-12831,
                -12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,-12320,-12300,
                -12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,
                -11781,-11604,-11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,
                -11055,-11052,-11045,-11041,-11038,-11024,-11020,-11019,-11018,-11014,-10838,-10832,
                -10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,-10329,-10328,
                -10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254
                ];

        /// <summary>
        /// 定义拼音数组
        /// </summary>
        private static readonly string[] getStr =
                [
                "A","Ai","An","Ang","Ao","Ba","Bai","Ban","Bang","Bao","Bei","Ben",
                "Beng","Bi","Bian","Biao","Bie","Bin","Bing","Bo","Bu","Ba","Cai","Can",
                "Cang","Cao","Ce","Ceng","Cha","Chai","Chan","Chang","Chao","Che","Chen","Cheng",
                "Chi","Chong","Chou","Chu","Chuai","Chuan","Chuang","Chui","Chun","Chuo","Ci","Cong",
                "Cou","Cu","Cuan","Cui","Cun","Cuo","Da","Dai","Dan","Dang","Dao","De",
                "Deng","Di","Dian","Diao","Die","Ding","Diu","Dong","Dou","Du","Duan","Dui",
                "Dun","Duo","E","En","Er","Fa","Fan","Fang","Fei","Fen","Feng","Fo",
                "Fou","Fu","Ga","Gai","Gan","Gang","Gao","Ge","Gei","Gen","Geng","Gong",
                "Gou","Gu","Gua","Guai","Guan","Guang","Gui","Gun","Guo","Ha","Hai","Han",
                "Hang","Hao","He","Hei","Hen","Heng","Hong","Hou","Hu","Hua","Huai","Huan",
                "Huang","Hui","Hun","Huo","Ji","Jia","Jian","Jiang","Jiao","Jie","Jin","Jing",
                "Jiong","Jiu","Ju","Juan","Jue","Jun","Ka","Kai","Kan","Kang","Kao","Ke",
                "Ken","Keng","Kong","Kou","Ku","Kua","Kuai","Kuan","Kuang","Kui","Kun","Kuo",
                "La","Lai","Lan","Lang","Lao","Le","Lei","Leng","Li","Lia","Lian","Liang",
                "Liao","Lie","Lin","Ling","Liu","Long","Lou","Lu","Lv","Luan","Lue","Lun",
                "Luo","Ma","Mai","Man","Mang","Mao","Me","Mei","Men","Meng","Mi","Mian",
                "Miao","Mie","Min","Ming","Miu","Mo","Mou","Mu","Na","Nai","Nan","Nang",
                "Nao","Ne","Nei","Nen","Neng","Ni","Nian","Niang","Niao","Nie","Nin","Ning",
                "Niu","Nong","Nu","Nv","Nuan","Nue","Nuo","O","Ou","Pa","Pai","Pan",
                "Pang","Pao","Pei","Pen","Peng","Pi","Pian","Piao","Pie","Pin","Ping","Po",
                "Pu","Qi","Qia","Qian","Qiang","Qiao","Qie","Qin","Qing","Qiong","Qiu","Qu",
                "Quan","Que","Qun","Ran","Rang","Rao","Re","Ren","Reng","Ri","Rong","Rou",
                "Ru","Ruan","Rui","Run","Ruo","Sa","Sai","San","Sang","Sao","Se","Sen",
                "Seng","Sha","Shai","Shan","Shang","Shao","She","Shen","Sheng","Shi","Shou","Shu",
                "Shua","Shuai","Shuan","Shuang","Shui","Shun","Shuo","Si","Song","Sou","Su","Suan",
                "Sui","Sun","Suo","Ta","Tai","Tan","Tang","Tao","Te","Teng","Ti","Tian",
                "Tiao","Tie","Ting","Tong","Tou","Tu","Tuan","Tui","Tun","Tuo","Wa","Wai",
                "Wan","Wang","Wei","Wen","Weng","Wo","Wu","Xi","Xia","Xian","Xiang","Xiao",
                "Xie","Xin","Xing","Xiong","Xiu","Xu","Xuan","Xue","Xun","Ya","Yan","Yang",
                "Yao","Ye","Yi","Yin","Ying","Yo","Yong","You","Yu","Yuan","Yue","Yun",
                "Za", "Zai","Zan","Zang","Zao","Ze","Zei","Zen","Zeng","Zha","Zhai","Zhan",
                "Zhang","Zhao","Zhe","Zhen","Zheng","Zhi","Zhong","Zhou","Zhu","Zhua","Zhuai","Zhuan",
                "Zhuang","Zhui","Zhun","Zhuo","Zi","Zong","Zou","Zu","Zuan","Zui","Zun","Zuo"
               ];
        /// <summary>
        /// 将汉字转换拼音的方法
        /// </summary>
        /// <param name="str">汉字字符串</param>
        /// <returns>拼音字符串</returns>
        public static string GetABC(string str)
        {
            Regex reg = new("^[\u4e00-\u9fa5]$");  //验证输入是否为汉字
            byte[] arr = new byte[2];              //定义字节数组
            string pystr = "";                     //定义字符串变量用于返回拼音
            char[] mChar = str.ToCharArray();      //获取汉字对应的字符数组
            return GetStr(mChar, pystr, reg, arr); //返回获取到的汉字拼音
        }

        private static string GetStr(char[] mChar, string pystr, Regex reg, byte[] arr)
        {
            ArgumentNullException.ThrowIfNull(arr); //null检查

            for (int j = 0; j < mChar.Length; j++)
            {
                if (reg.IsMatch(mChar[j].ToString()))//如果输入的是汉字
                {
                    arr = Encoding.Default.GetBytes(mChar[j].ToString());
                    int M1 = arr[0];
                    int M2 = arr[1];
                    int asc = M1 * 256 + M2 - 65536;
                    if (asc > 0 && asc < 160)
                    {
                        pystr += mChar[j];
                    }
                    else
                    {
                        switch (asc)
                        {
                            case -9254:
                                pystr += "Zhen"; break;
                            case -8985:
                                pystr += "Qian"; break;
                            case -5463:
                                pystr += "Jia"; break;
                            case -8274:
                                pystr += "Ge"; break;
                            case -5448:
                                pystr += "Ga"; break;
                            case -5447:
                                pystr += "La"; break;
                            case -4649:
                                pystr += "Chen"; break;
                            case -5436:
                                pystr += "Mao"; break;
                            case -5213:
                                pystr += "Mao"; break;
                            case -3597:
                                pystr += "Die"; break;
                            case -5659:
                                pystr += "Tian"; break;
                            default:
                                for (int i = (getValue.Length - 1); i >= 0; i--)
                                {
                                    if (getValue[i] <= asc)//判断汉字的拼音区编码是否在指定范围内
                                    {
                                        pystr += getStr[i];//如果不超出范围则获取对应的拼音
                                        break;
                                    }
                                }
                                break;
                        }
                    }
                }
                else//如果不是汉字
                {
                    pystr += mChar[j].ToString();         //如果不是汉字则返回
                }
            }
            return pystr;
        }

        //[GeneratedRegex("^[\u4e00-\u9fa5]$")]
        //private static partial Regex MyRegex();
    }
}

三、生成效果

四、实例中的知识点 

1.Regex

2.ToCharArray()

3.IsMatch()

4.GetBytes()

         详见本文作者的其它文章,C#中汉字转区位码-CSDN博客  https://blog.csdn.net/wenchm/article/details/135350559?spm=1001.2014.3001.5501

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/288639.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

前缀和算法 -- 寻找数组的中心坐标

个人主页&#xff1a;Lei宝啊 愿所有美好如期而遇 本题链接 力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台 输入描述 给定一个数组&#xff0c;接口为int pivotIndex(vector<int>& nums) 输出描述 我们以示例1为例画图解释&#xf…

【Win】没设置Windows账户密码,如何远程登录

1、按下Win&#xff0c;输入本地&#xff0c;打开本地安全策略 2、找到这个 3、双击打开&#xff0c;改成已禁用 4、正常重新启动一次或者开关机一次永久生效。 - 我第一次弄完死机了&#xff0c;再开机发现没生效

前端基础:Vue搞笑白话文(工作之余瞎写)

1、data:{}与data(){return{}}这两个是个什么鬼&#xff1f; vue实例 new Vue({el:#app,data:{name:李四}}) 组件实例 const aaa Vue.extent({data(){return {name:}} }) 为什么Vue实例可以那么写而组件实例就不行了&#xff1f;原因就是因为在底层原理上&#xff0c;组件…

七:Day06_redis高级01

第一章 Redis入门 1.1 节 什么是NoSql型数据库 NoSQL ,泛指非关系型的数据库, NoSQL Not Only SQL,它可以作为关系型数据库的良好补充。NoSQL 不依赖业务逻辑方式存储&#xff0c;而以简单的key-value模式存储。因此大大的增加了数据库的扩展能力。 SQLNoSQL数据结构结构化非…

DevChat助手:在数据库及数据分析上面的应用实践

&#x1f3c6;作者简介&#xff0c;黑夜开发者&#xff0c;CSDN领军人物&#xff0c;全栈领域优质创作者✌&#xff0c;CSDN博客专家&#xff0c;阿里云社区专家博主&#xff0c;2023年6月CSDN上海赛道top4。 &#x1f3c6;数年电商行业从业经验&#xff0c;历任核心研发工程师…

Vue 中的 ref 与 reactive:让你的应用更具响应性(下)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

uniapp选择android非图片文件的方案踩坑记录

这个简单的问题我遇到下面6大坑&#xff0c;原始需求是选择app如android的excel然后读取到页面并上传表格数据json 先看看效果 uniapp 选择app excel文件读取 1.uniapp自带不支持 uniapp选择图片和视频非常方便自带已经支持可以直接上传和读取 但是选择word excel的时候就出现…

【每日一题】466. 统计重复个数-2024.1.2

题目&#xff1a; 466. 统计重复个数 定义 str [s, n] 表示 str 由 n 个字符串 s 连接构成。 例如&#xff0c;str ["abc", 3] "abcabcabc" 。 如果可以从 s2 中删除某些字符使其变为 s1&#xff0c;则称字符串 s1 可以从字符串 s2 获得。 例如&…

javascript中location对象的属性与方法

前言 本章介绍js中的location中的属性和方法。 文章目录 前言什么是location为什么要用locationlocation对象属性location对象方法总结 什么是location 在JavaScript中&#xff0c;location 是一个包含当前页面的URL信息的对象。它允许你获取和操作当前页面的URL&#xff0c;比…

数字IC设计——数字电路基本元器件

现代数字集成电路基本由CMOS晶体管构成&#xff0c;而CMOS门电路由PMOS场效应管和NMOS场效应管以对称互补的形式组成&#xff0c;所谓“互补”&#xff0c;即利用互补型MOSFET&#xff0c;即pMOS和nMOS&#xff0c;二者成对出现构成互补电路。 这种电路具有高的电路可靠性和抗干…

向日葵远程控制软件MySQL5.7的安装与配置

目录 一. 向日葵远程控制软件 1.1 简介 1.2 选择原因 1.3 安装及使用 1.4 使用场景 二. MySQL5.7 安装与配置 2.1 什么是MySQL 2.2 安装 MySQL5.7 2.2.1 安装步骤 2.2.2 内部连接 2.2.3 外部连接 三. 思维导图 一. 向日葵远程控制软件 1.1 简介 向日葵电脑版是一款拥有多年…

Mybatis获取参数值得两种方式:${}和#{},${}和#{}区别是什么?

${}的本质是字符串拼接&#xff0c;#{}的本质是占位符赋值 ${} 使用字符串拼接的方式拼接sql&#xff0c;若为字符串类型或日期类型的字段进行赋值时&#xff0c;需要手动加单引号&#xff1b; #{} 使用占位符赋值的方式拼接sql&#xff0c;此时为字符串类型或日期类型的字段…

Halcon顶帽运算与底帽运算的应用

Halcon顶帽运算与底帽运算的应用 文章目录 Halcon顶帽运算与底帽运算的应用1. 提取小的物件2. 校正非均匀光照 正如上文所说的&#xff0c;顶帽运算返回的像素部分是尺寸比结构元素小的&#xff0c;并且比较亮的局部小区域&#xff1b;底帽运算返回的像素部分是尺寸比结构元素小…

陆面过程模式CLM、地球系统模式CESM安装及快速运行

目录 专题一 CESM、CLM运行条件及Linux编译基础 专题二 CESM、CLM基础 专题三 CLM程序获取、结构及其功能 专题四 CLM移植、安装及快速运行 专题五 CLM配置选项及数据文件制备 专题六 CLM单点或区域运行 专题七 CLM结果处理、分析及可视化 专题八 CLM代码修改、发展及改…

旧电脑搭建NAS

旧电脑可以搭建NAS吗&#xff1f; 可以&#xff01; 性能好吗&#xff1f; 完全没问题&#xff01; 简单吗&#xff1f; 轻松上手&#xff01; 怎吗搭建&#xff1f; 这里&#xff1a;用旧电脑搭建NAS在您的家庭中&#xff0c;通过将旧 PC 转变为NAS服务器&#xff0c;您…

纯css实现三等分饼图

实现原理&#xff0c;先绘制一个圆&#xff0c;然后把圆分成两份&#xff0c;在绘制一个菱形&#xff0c;最下面的角是120&#xff0c;这样就可以实现三等分啦 关键代码是一个css很少见的属性clip-path clip-path: polygon(24rem 36rem, 48rem 18rem, 24rem 0, 0 18rem); &…

【一文入门】Git常用命令集锦--分支操作和版本管理篇

前言 Git 是一种分布式版本控制系统&#xff0c;可以帮助团队协作开发、管理和维护代码&#xff0c;提高代码质量和效率&#xff0c;掌握常用版本管理命令可以帮助我们更好地管理代码变更和历史记录。下面我将介绍开发中常用的一些Git分支操作和版本管理命令 1 分支操作 1.1 …

MySQL——事物

目录 一.发现问题 二.什么时事物 三.事务提交方式 四.事物的常规操作方式 五. 事务隔离级别 1.如何理解隔离性 2.隔离级别 3.查看与设置隔离性 4.读未提交【Read Uncommitted】 5.读提交【Read Committed】 6.可重复读【Repeatable Read】 7.串行化【serializabl…

什么是 NAS?

一、什么是 NAS&#xff1f; 在数字化时代&#xff0c;小型企业面临着日益增长的数据存储需求。为了应对这一挑战&#xff0c;网络附加存储&#xff08;NAS&#xff09;系统成为了许多企业的首选解决方案。NAS系统是一种连接到网络的存储设备&#xff0c;允许授权网络用户和异…

声明式的管理方法文件

1.声明式管理方法&#xff08;yaml&#xff09;文件 1.适合对资源的修改操作 2.声明式管理依赖于已有yaml文件&#xff0c;所有的内容都在yaml文件中声明 3.编辑好的yaml文件还是要依靠陈述式的命令发布到k8s集群当中 2.声明式的三种格式 1.deployment的yaml文件 demonset…