美文网首页.NETC#dotNET
第3章 字符串处理技术

第3章 字符串处理技术

作者: 张中华 | 来源:发表于2018-08-29 20:16 被阅读26次

目录

实例1:汉字转换成汉语拼音(支持多音字)

实例2: 将字符串的每个字符进行颠倒输出

实例3:从字符串中分离文件路径、文件名及扩展名


实例1:汉字转换成汉语拼音

我之前在一篇文章中,了解过一些汉字转换成拼音的方式:https://www.jianshu.com/p/d9d830673a77
对于一些多音字的处理,如果有需要,可以特别定制一下。

然而,今天无意间,发现一个引用,貌似解决了这个问题。

添加ChineseConvertPinyin引用。
使用方式:

 static void Main(string[] args)
        {
            string chinese = "音乐,乐器,快乐,你和我,应和,和稀泥";
            ChineseConvertPinyin.ChineseToPinyin CTP = new ChineseConvertPinyin.ChineseToPinyin();
            var result = CTP.GetFullPinyin(chinese);

            Console.WriteLine(result);
            Console.ReadLine();
        }

连“和稀泥”都识别了,可见对多音字的识别已经做到很好了。

实例2: 将字符串的每个字符进行颠倒输出

将Hello world! 颠倒输出:
实现效果:



实现代码:

static void Main(string[] args)
        {
            string text = "Hello world!";
            char[] ch = text.ToArray();
            Array.Reverse(ch,0,text.Length);
            Console.WriteLine("颠倒后的字符串输出:"  + new StringBuilder().Append(ch).ToString());
            Console.ReadLine();
        }

注意,这里使用的Array类提供的方法,而不是char类型里面的方法。
其次,输出时,也是将字符存入StringBuilder后tostring(),直接将char.tostring()的话,得到的时system.char[]。

实例3:从字符串中分离文件路径、文件名及扩展名

实现效果:



实现代码:

private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = openFileDialog.FileName;
                this.textBox1.Text = file.Substring(0, file.LastIndexOf("\\") + 1);
                this.textBox2.Text = file.Split('\\')[file.Split('\\').Length - 1].Split('.')[0];
                this.textBox3.Text = file.Split('\\')[file.Split('\\').Length - 1].Split('.')[1];
            }
        }

实例4: 获取字符串中汉字的个数

判断字符串“一个汉字,is right?”汉字个数。
实现效果:



实现代码:

static void Main(string[] args)
        {
            int count = 0;
            string hanzi = "一个汉字,is right?";
            Regex P_regex = new Regex("^[\u4E00-\u9FA5]{0,}$"); //创建正则表达式对象,用于判断字符是否为汉字
            for (int i = 0; i < hanzi.Length; i++)
            {
                count = P_regex.IsMatch(hanzi[i].ToString()) ? ++count:count;
            }
            Console.WriteLine("汉字个数:" + count.ToString());
            Console.ReadLine();
        }

相关文章

网友评论

    本文标题:第3章 字符串处理技术

    本文链接:https://www.haomeiwen.com/subject/icucwftx.html