开发者

Inputs a sentence from user, determines and displays nonduplicate words in alphabetical order

The official question: Write a console application that inputs a sentence from the user (assume no punctuation), then determines and displays the non-duplicate words in alphabetical order. Treat uppercase and lowercase letters the same. [Hint: You can use string method Split with no arguments, as in sentence.Split(), to break a sentence into an array of strings containing the individual words. By default, Split uses spaces as delimiters. Use string method ToLower in the select and orderby clauses of your LINQ query to obtain the lowercase version of each word.]

This is what I have so far:

static void Main(string[] args)
        {   // Creates list o开发者_运维知识库f type string
            List<string> list = new List<string>();
            // Writes for sentence
            Console.Write("Enter your sentence. No punctuation.   : ");
            // Converts console into string
            string sent = (Console.ReadLine());
            // Splits string into array
            string[] words = sent.Split();
            // Writes array to list
            for (int i = 0; i < words.Length; i++)
            {
                list.Add(words[i]);
            }
            // Sorts words
            var sort =
                from word in list
                let lowerWord = word.ToLower()
                orderby lowerWord
                select lowerWord;

            // I assume a var query goes here to delete dup words

            // Writes words
            foreach (string c in sort)
            {
                Console.WriteLine(c);
            }
        }

I don't know how to find the duplicates and delete them.


Would

var unique = sort.Distinct();

work for you?


    public static IEnumerable<string> GetAlphabetizedUniqueWords(string sentence)
    {
        return (sentence ?? string.Empty)
            .Split()
            .Select(x => x.ToLowerInvariant())
            .Distinct()
            .OrderBy(x => x);
    }


    static void Main( )
    {
        Console.Write("Enter your sentence. No punctuation.   : ");
        foreach (var word in GetAlphabetizedUniqueWords(Console.ReadLine()))
            Console.WriteLine(word);
    }


After sorting, walk the list, and compare each word to the previous. If they match, delete the word. Since the list is sorted, all the duplicates must be adjacent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜