2013-11-10 32 views
0

该程序计算并显示用户正在键入的单词数和字符数。 “字计数器”工作正常,但我不知道如何计算字符而不计算其间的空格。C# - 显示字符数不计空格?

private void userTextBox_TextChanged(object sender, EventArgs e) 
{ 
    string userInput = userTextBox.Text; 
    userInput = userInput.Trim(); 
    string[] wordCount = userInput.Split(null); 

    //Here is my error 
    string[] charCount = wordCount.Length; 

    wordCountOutput.Text = wordCount.Length.ToString(); 
    charCountOutput.Text = charCount.Length.ToString(); 
} 

回答

4

因为你的名字是“Learning2Code”我想我给你解决使用至少先进的技术,原来的尝试回答:

private void userTextBox_TextChanged(object sender, EventArgs e) 
{ 
    string userInput = userTextBox.Text; 
    userInput = userInput.Trim(); 
    string[] wordCount = userInput.Split(null); 

    int charCount = 0; 
    foreach (var word in wordCount) 
     charCount += word.Length; 

    wordCountOutput.Text = wordCount.Length.ToString(); 
    charCountOutput.Text = charCount.ToString(); 
} 
+0

好吧真棒!这很好。谢谢亚伦! – Learnin2Code

4

你可以使用LINQ没有白空格字符计数:

int charCount = userInput.Count(c => !Char.IsWhiteSpace(c)); 

然而,你的代码表明,你只是不知道如何来算的话,那么

更换

string[] charCount = wordCount.Length; 

int words = wordCount.Length; 
+0

的第一行代码完美的作品。我只是不得不从底部删除“.Lenghth”。感谢Tim – Learnin2Code

0

只是正则表达式替换所有的空格(新行字符):

Regex.Replace(inputString, "[\s\n]", ""); 
+5

我几乎认为一个正则表达式不适合这个任务! –

+0

你为什么这么认为? – Agat

+1

更重要的是,你为什么这么认为!提示:不要引入复杂性。作为一名程序员,您的工作是降低复杂性! –

2

你已经每一个字,所以算在每个字的字符,总结总:

var charCount = words.Sum(w => w.Length); 

注意:您将单词数组存储为“wordCount” - 我在上面的代码片段中将其重命名为“单词”以便语义正确。即:

string[] words = userInput.Split(null); 
0

没有比单词数少一个空格(例如"once upon a time"包含四个单词和三个空格),这样你就可以计算出的空格数。然后,只需减去的空格数从输入字符串的长度:

int charCount = userInput.Length - (wordCount.Length - 1); 

作为该是一个整数,而不是一个字符串数组,不使用Length当输出结果:

charCountOutput.Text = charCount.ToString();