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);
}
}
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);
}
}
Change this line:
string[] words = x.Split(delimiterChars);
in
string[] words = x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
The problem is that multiple delimiters appear after the other, so the array really does not contain delimiters, but null
values where there is no word between delimiters. This can be prevented by using
x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries)