目录
????????字符串中可以包括数字、字母、汉字或者其他字符。使用Char类型的IsDigit静态方法可以判断字符串中的某个字符是否为数字,使用Char类型的IsLetter静态方法可以判断字符串中的某个字符是否为字母。
????????使用正则表达式判断字符是否为汉字,进一步了解字符串是一组不可变的字符集的概念,可以使用索引访问字符串中的每一个字符。
????????字符串对象的索引是只读的,只可以读取字符串对象中的字符,不可以根据索引更改字符串中的字符。
Regex regex = MyRegex(); ? ? ? ? ? ? ? ?//创建正则表达式对象,用于判断字符是否为汉字
[GeneratedRegex("^[\u4E00-\u9FA5]{0,}$")]
private static partial Regex MyRegex();
// 用正则表达式获取字符串中汉字的个数
using System.Text.RegularExpressions;
namespace _044
{
public partial class Form1 : Form
{
private GroupBox? groupBox1;
private TextBox? textBox2;
private TextBox? textBox1;
private Button? button1;
private Label? label2;
private Label? label1;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// textBox2
//
textBox2 = new TextBox
{
Location = new Point(117, 48),
Name = "textBox2",
Size = new Size(133, 23),
TabIndex = 4,
};
//
// textBox1
//
textBox1 = new TextBox
{
Location = new Point(117, 18),
Name = "textBox1",
Size = new Size(162, 23),
TabIndex = 3
};
//
// button1
//
button1 = new Button
{
Location = new Point(17, 48),
Name = "button1",
Size = new Size(97, 23),
TabIndex = 2,
Text = "获取汉字数量",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// label2
//
label2 = new Label
{
AutoSize = true,
Location = new Point(259, 50),
Name = "label2",
Size = new Size(20, 17),
TabIndex = 1,
Text = "个"
};
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(17, 24),
Name = "label1",
Size = new Size(80, 17),
TabIndex = 0,
Text = "输入字符串:"
};
//
// groupBox1
//
groupBox1 = new GroupBox
{
Location = new Point(12, 12),
Name = "groupBox1",
Size = new Size(285, 77),
TabIndex = 0,
TabStop = false,
Text = "获取汉字数量"
};
groupBox1.Controls.Add(textBox2);
groupBox1.Controls.Add(textBox1);
groupBox1.Controls.Add(button1);
groupBox1.Controls.Add(label2);
groupBox1.Controls.Add(label1);
groupBox1.SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(309, 101);
Controls.Add(groupBox1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "获取字符串中汉字的数量";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
}
private void Button1_Click(object? sender, EventArgs e)
{
int temp = 0; //用于存储汉字数量
Regex regex = MyRegex(); //创建正则表达式对象,用于判断字符是否为汉字
for (int i = 0; i < textBox1!.Text.Length; i++)//遍历字符串中每一个字符
{
temp = regex.IsMatch(textBox1.Text[i]. //如果字符是汉字则计数器加1
ToString()) ? ++temp : temp;
}
textBox2!.Text = temp.ToString(); //显示汉字数量
}
[GeneratedRegex("^[\u4E00-\u9FA5]{0,}$")]
private static partial Regex MyRegex();
}
}
?
? ? ? ? ?详见本文作者写的其他文章,C#中使用正则表达式实现汉字转拼音-CSDN博客 ?https://wenchm.blog.csdn.net/article/details/135374006
?