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

C#实现统计字数功能的方法

程序员文章站 2023-12-03 16:43:40
本文实例讲述了c#实现统计字数功能的方法。分享给大家供大家参考。具体如下: 1.程序效果示例如下: 2.程序控件用法: 3.程序代码: using...

本文实例讲述了c#实现统计字数功能的方法。分享给大家供大家参考。具体如下:

1.程序效果示例如下:

C#实现统计字数功能的方法

2.程序控件用法:

C#实现统计字数功能的方法

3.程序代码:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;
using system.io;
namespace program18
{
 public partial class formmain : form
 {
  public formmain()
  {
   initializecomponent();
  }
  private void btnread_click(object sender, eventargs e)
  {
   try
   {
    txtwords.text = file.readalltext(txtfileaddr.text);
   }
   catch (exception ex)
   { 
    messagebox.show(ex.message);
   }
  }
  private void txtwords_textchanged(object sender, eventargs e)
  {
   int iallchr = 0; //字符总数:不计字符'\n'和'\r'
   int ichinesechr = 0; //中文字符计数
   int ichinesepnct = 0;//中文标点计数
   int ienglishchr = 0; //英文字符计数
   int ienglishpnct = 0;//中文标点计数
   int inumber = 0;  //数字字符:0-9
   foreach (char ch in txtwords.text)
   {
    if (ch != '\n' && ch != '\r') iallchr++;
    if ("~!@#¥%…&()—+-=".indexof(ch) != -1 ||
     "{}【】:“”;‘'《》,。、?|\".indexof(ch) != -1) ichinesepnct++;
    if (ch >= 0x4e00 && ch <= 0x9fbb) ichinesechr++;
    if ("`~!@#$%^&*()_+-={}[]:\";'<>,.?/\\|".indexof(ch) != -1) ienglishpnct++;
    if ((ch >= 'a' && ch <= 'z') || (ch >= 'a' && ch <= 'z')) ienglishchr++;
    if (ch >= '0' && ch <= '9') inumber++;
   }
   string sstats = string.format(string.concat(
    "字符总数:{0}\r\n", "中文字符数:{1}\r\n", "中文标点数:{2}\r\n",
    "英文字符数:{3}\r\n", "英文标点数:{4}\r\n", "数字字符数:{5}\r\n"),
    iallchr.tostring(), ichinesechr.tostring(), ienglishchr.tostring(),
    ienglishchr.tostring(), ienglishpnct.tostring(), inumber.tostring());
   txtstats.text = sstats;
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。