C # how not to count delimiter characters as a word
I have to enter a sentence like Hello, my name is Ann! and it will print the word count which is 5 and print the words as such: Hello my name is Ann
however mine counts as special characters in word form, so my sentence above counts as 7 words. 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);
}
}
+3
user4840466
source
to share
3 answers
In the program, you count 2 blank entries. This is due to the combination of comma and space. For example, it creates an array entry for 0-character notation in between. You can avoid this by using StringSplitOptions.RemoveEmptyEntries
.
Then the code should look like this:
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);
}
}
+2
source to share