句子中的单词数?(C#控制台应用程序) [英] Number of Words in a Sentence?(C# Console App)
本文介绍了句子中的单词数?(C#控制台应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi all. i wanna write c# console app that compute " Number of Words in a Sentence"
and i write this code but it's a big problem that if number of "Space" in between sentence more than one the program output is Wrong.
using System;
namespace Test
{
class Program
{
static void Main()
{
string st1 = " this is a test ";
// First character
char firstChar = 'a';
int counter = 0;
int indexfirstChar = 0;
char lastChar = 'l';
int indexLastChar = 0;
for (int i = 0; i < st1.Length; i++)
{
if (char.IsLetter(st1[i]) || char.IsDigit(st1[i]))
{
firstChar = st1[i];
indexfirstChar = i;
break;
}
}
// latest character
for (int i = st1.Length - 1; i >= 0; i--)
{
if (char.IsLetter(st1[i]) || char.IsDigit(st1[i]))
{
lastChar = st1[i];
indexLastChar = i;
break;
}
}
for (int i = indexfirstChar; i < indexLastChar + 1; i++)
{
if (st1[i].ToString() == " ")
counter++;
}
Console.WriteLine(" Number of Word:" + counter + 1);
}
}
}
推荐答案
您可以使用以下代码计算单词数:
You can use this code to count the number of words:
using System;
namespace Test {
public class Program
{
public void Main()
{
string st1 = " this is a test ";
char[] seperator = new char[] { ' ' };
int numberOfWords = st1.Split(seperator,StringSplitOptions.RemoveEmptyEntries).Length + 1;
Console.WriteLine("Number of words: {0}", numberOfWords);
}
}
}
希望对您有所帮助.
Hope this helps.
为什么不尝试简单的方法?
Why not try it the simple way?
string source = "This is a sentence, that I want to check - no, really, I do!";
string[] parts = source.Split(new char[] { ' ', '.', '!', '?' }, StringSplitOptions.RemoveEmptyEntries);
它可能需要一些调整,但基本上可以完成您想要的操作.
It may need a little tweaking, but it will basically do what you want.
Quote:
(int i = indexfirstChar; i< indexLastChar +1; i ++)
{
如果(st1 [i] .ToString()==")
counter ++;
}
for (int i = indexfirstChar; i < indexLastChar + 1; i++)
{
if (st1[i].ToString() == " ")
counter++;
}
更改为:
Change to:
bool newspace = false;
for (int i = indexfirstChar; i < indexLastChar + 1; i++)
{
if (st1[i].ToString() == " ")
{
if (! newspace )
{
counter++;
newspace = true;
}
}
else
{
if ( newspace )
{
newspace = false;
}
}
}
顺便说一句,我想您应该在结果中添加1
(我们实际上是在计算空白序列的出现).
BTW I suppose you should add 1
to the result (we''re actually counting blank sequences occurrences).
这篇关于句子中的单词数?(C#控制台应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文