Eric Lippert's challenge “comma-quibbling”, best answer?

后端 未结 27 2242
日久生厌
日久生厌 2020-12-01 06:59

I wanted to bring this challenge to the attention of the stackoverflow community. The original problem and answers are here. BTW, if you did not follow it before, you should

27条回答
  •  半阙折子戏
    2020-12-01 07:01

    How about this approach? Purely cumulative - no back-tracking, and only iterates once. For raw performance, I'm not sure you'll do better with LINQ etc, regardless of how "pretty" a LINQ answer might be.

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    static class Program
    {
        public static string CommaQuibbling(IEnumerable items)
        {
            StringBuilder sb = new StringBuilder('{');
            using (var iter = items.GetEnumerator())
            {
                if (iter.MoveNext())
                { // first item can be appended directly
                    sb.Append(iter.Current);
                    if (iter.MoveNext())
                    { // more than one; only add each
                      // term when we know there is another
                        string lastItem = iter.Current;
                        while (iter.MoveNext())
                        { // middle term; use ", "
                            sb.Append(", ").Append(lastItem);
                            lastItem = iter.Current;
                        }
                        // add the final term; since we are on at least the
                        // second term, always use " and "
                        sb.Append(" and ").Append(lastItem);
                    }
                }
            }
            return sb.Append('}').ToString();
        }
        static void Main()
        {
            Console.WriteLine(CommaQuibbling(new string[] { }));
            Console.WriteLine(CommaQuibbling(new string[] { "ABC" }));
            Console.WriteLine(CommaQuibbling(new string[] { "ABC", "DEF" }));
            Console.WriteLine(CommaQuibbling(new string[] {
                 "ABC", "DEF", "G", "H" }));
        }
    }
    

提交回复
热议问题