我想计算文本框中的字符数和单词数.我怎样才能做到这一点? [英] I want to count number of chars and words from textbox. How can I do this?

查看:130
本文介绍了我想计算文本框中的字符数和单词数.我怎样才能做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过此操作,它给出了正确的字符数,但没有给出单词数.

我尝试过的事情:

I tried this it gives the correct num of character but not give the num of word.

What I have tried:

if (txtStringName.Value != " ")
{
    str = txtStringName.Value.ToString().Trim();
    for (i = 0; i != str.Length; i++)
    {
        ch++;
        if (str == " ")
            word++;
    }
}

推荐答案

仅出于乐趣,您可以使用两个正则表达式来实现.
Just for the fun of it you can do it with two regular expressions.
int wordCount = Regex.Matches(txtStringName.Value, "\\w+").Count;
int charCount = Regex.Matches(txtStringName.Value, "\\w").Count;


您好,请参考以下代码,
Hello, refer this code,
int NoOfWords = 0;
int NoOfChars = 0;
string objText = textBox1.Text.Trim();

string[] words = objText.Split(' ');
NoOfWords = words.Length;

foreach (string word in words)
{
    NoOfChars += word.Length;
}

MessageBox.Show(string.Format("Words {0} and Chars {1}", NoOfWords, NoOfChars));


只需做一些分析,并在实现之前进行逻辑思考,因为这是一个非常简单的场景.


Just do some analysis, and think logically before implementing, because it is a very simple scenario.


尝试一下

try this

string Value = "Today is Friday";
       int CharCount = 0;
       int wordsCount = 0;
       if (Value != "")
       {
           wordsCount++;
           for (int i = 0; i < Value.Length; i++)
           {
               CharCount++;
               if (Value[i] == ' ')
                   wordsCount++;
           }
       }

       Console.WriteLine("Char Count = " + CharCount);
       Console.WriteLine("Words Count = " + wordsCount);
       Console.ReadKey();



最简单的方法是



Simplest way is

CharCount = Value.Length;
 wordsCount = Value.Split(' ').Length;


这篇关于我想计算文本框中的字符数和单词数.我怎样才能做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆