我能够计算文本框中的字符数。但我不知道如何计算单词的数量并将它们打印成标签。
答案 0 :(得分:5)
假设您使用空格区分每个单词,请尝试以下操作: -
int count = YourtextBoxId.Text
.Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries)
.Count();
正如@Tim Schmelter建议的那样,如果除了空白区域之外你有不同的分隔符,你可以扩展它: -
int count = YourtextBoxId.Text
.Split(new char[] {' ','.',':'},StringSplitOptions.RemoveEmptyEntries)
.Count();
答案 1 :(得分:4)
第一点是" WORD"的定义。你应该在实现代码之前知道它。
因此,如果WORD定义为一系列字母,您可以使用以下代码计算单词数:
public int WordsCount(string text)
{
if (string.IsNullOrEmpty(text))
{
return 0;
}
var count = 0;
var word = false;
foreach (char symbol in text)
{
if (!char.IsLetter(symbol))
{
word = false;
continue;
}
if (word)
{
continue;
}
count++;
word = true;
}
return count;
}
答案 2 :(得分:3)
您可以像以下示例一样使用Regex.Matches()
:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
const string t1 = "To be or not to be, that is the question.";
Console.WriteLine(WordCounting.CountWords1(t1));
Console.WriteLine(WordCounting.CountWords2(t1));
const string t2 = "Mary had a little lamb.";
Console.WriteLine(WordCounting.CountWords1(t2));
Console.WriteLine(WordCounting.CountWords2(t2));
}
}
/// <summary>
/// Contains methods for counting words.
/// </summary>
public static class WordCounting
{
/// <summary>
/// Count words with Regex.
/// </summary>
public static int CountWords1(string s)
{
MatchCollection collection = Regex.Matches(s, @"[\S]+");
return collection.Count;
}
/// <summary>
/// Count word with loop and character tests.
/// </summary>
public static int CountWords2(string s)
{
int c = 0;
for (int i = 1; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i - 1]) == true)
{
if (char.IsLetterOrDigit(s[i]) == true ||
char.IsPunctuation(s[i]))
{
c++;
}
}
}
if (s.Length > 2)
{
c++;
}
return c;
}
}
答案 3 :(得分:1)
MyTextbox.Text.Split(' ').Count()
答案 4 :(得分:1)
您可以尝试使用空格在文本框中拆分字符串。
string[] words = textbox.Text.Split(' '); // <-- Space character
int numberOfWords = words.Length;
label.Text = "Number of words are: " + numberOfWords;
答案 5 :(得分:1)
这对我有用..
var noOfWords = Regex.Replace(textBox1.Text, "[^a-zA-Z0-9_]+", " ")
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Length;