[英]c# how to not count delimiter characters as a word
I'm supposed to type in a sentence eg Hello, my name is Ann! 我应该输入一个句子,例如Hello,我的名字叫Ann! and it will print out the number of words which is 5 and print out the words as such: Hello my name is Ann 它将打印出5个单词的数量并打印出来的单词:你好我的名字是Ann
however mine counts the special characters in as a word and so my sentence above is considered to have 7 words. 然而,我的特殊字符作为一个单词计算,所以我的上面的句子被认为有7个单词。 Please help! 请帮忙! Thank you in advance :) 先感谢您 :)
static void Main(string[] args)
{
char[] delimiterChars = { ' ', ',', '.', ':', '?', '!' };
Console.Write("Enter a sentence: ");
string x = Console.ReadLine();
Console.WriteLine("The sentence is: ", x);
string[] words = x.Split(delimiterChars);
Console.WriteLine("{0} words in text:", words.Length);
foreach (string s in words)
{
Console.WriteLine(s);
}
}
You program does count 2 empty entries in your sentence. 你的程序会在你的句子中计算2个空条目。 This happens due to the combination of comma and space. 这是因为逗号和空格的组合。 It creates an array-entry for the 0-character entry between them, for instance. 例如,它为它们之间的0字符条目创建一个数组条目。 You can avoid this using StringSplitOptions.RemoveEmptyEntries
. 您可以使用StringSplitOptions.RemoveEmptyEntries
避免这种情况。
The code should then look like: 代码应如下所示:
static void Main(string[] args)
{
char[] delimiterChars = { ' ', ',', '.', ':', '?', '!' };
Console.Write("Enter a sentence: ");
string x = "Hello, my name is Ann!";
Console.WriteLine("The sentence is: ", x);
string[] words = x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("{0} words in text:", words.Length);
foreach (string s in words)
{
Console.WriteLine(s);
}
}
Change this line: 改变这一行:
string[] words = x.Split(delimiterChars);
to: 至:
string[] words = x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
The problem is that multiple separators appear after another, so the array indeed does not contain any separator but null
values where there is no word between separators. 问题是多个分隔符出现在另一个之后,因此数组确实不包含任何分隔符,而是null
值,其中分隔符之间没有单词。 You can prevent this by using 您可以使用以防止这种情况
x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.