简体   繁体   中英

c# how to not count delimiter characters as a word

I'm supposed to type in a sentence eg Hello, my name is 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

however mine counts the special characters in as a word and so my sentence above is considered to have 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);
        }
    }

You program does count 2 empty entries in your sentence. This happens due to the combination of comma and space. It creates an array-entry for the 0-character entry between them, for instance. You can avoid this using 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. You can prevent this by using

x.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM