[英]c# how to not count delimiter characters as a word
我應該輸入一個句子,例如Hello,我的名字叫Ann! 它將打印出5個單詞的數量並打印出來的單詞:你好我的名字是Ann
然而,我的特殊字符作為一個單詞計算,所以我的上面的句子被認為有7個單詞。 請幫忙! 先感謝您 :)
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);
}
}
你的程序會在你的句子中計算2個空條目。 這是因為逗號和空格的組合。 例如,它為它們之間的0字符條目創建一個數組條目。 您可以使用StringSplitOptions.RemoveEmptyEntries
避免這種情況。
代碼應如下所示:
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);
}
}
改變這一行:
string[] words = x.Split(delimiterChars);
至:
string[] words = x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
問題是多個分隔符出現在另一個之后,因此數組確實不包含任何分隔符,而是null
值,其中分隔符之間沒有單詞。 您可以使用以防止這種情況
x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.