我试图创建一个方法来将字符串传递给方法,然后我想显示字符串中的单词数。该字符串是文本框中的用户输入。
private void button1_Click(object sender, EventArgs e)
{
countMethod();
}
private string countMethod()
{
String text = textBox1.Text.Trim();
int wordCount = 0, index = 0;
while (index < text.Length)
{
// check if current char is part of a word
while (index < text.Length && Char.IsWhiteSpace(text[index]) == false)
index++;
wordCount++;
// skip whitespace until next word
while (index < text.Length && Char.IsWhiteSpace(text[index]) == true)
index++;
}
return MessageBox.Show(wordCount.ToString());
}
编辑:
我在方法中添加了一个参数。循环完成后,将wordCount发送到字符串。我尝试了几次,它的工作原理。我是编程的新手,有没有理由说这不会起作用或应该采取另一种方式呢?感谢
private void button1_Click(object sender, EventArgs e)
{
string userInput = textBox1.Text;
countMethod(userInput);
}
private string countMethod(string input)
{
string text = textBox1.Text.Trim();
int wordCount = 0, index = 0;
while (index < text.Length)
{
// check if current char is part of a word
while (index < text.Length && Char.IsWhiteSpace(text[index]) == false)
index++;
wordCount++;
// skip whitespace until next word
while (index < text.Length && Char.IsWhiteSpace(text[index]) == true)
index++;
}
string total = wordCount.ToString();
MessageBox.Show("The total words in this string are: " +total);
return total;
}
答案 0 :(得分:3)
有一种更简单的方法!
private void button1_Click(object sender, EventArgs e)
{
var wordCount = CountWords(textBox1.Text);
MessageBox.Show(wordCount.ToString());
}
private int CountWords(string input)
{
var separators = new[] { ' ', '.' };
var count = input.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length;
return count;
}
在separators
数组中添加/删除所需的分隔符。
答案 1 :(得分:2)
尝试使用扩展方法。这是个好主意。
public static class MyExtentionClass
{
public static int WordCount(this string str)
{
var separators = new[] { ' ', '.', ',' };
var count = str.Split(separators, StringSplitOptions.RemoveEmptyEntries).Length;
return count;
}
}
例如:
MessageBox.Show(textBox1.Text.WordCount());
答案 2 :(得分:0)
拆分白色空格然后计算
int wordCount = textBox1.Text.Trim().Split(" ").Count;