Algorithm for joining e.g. an array of strings

后端 未结 16 1898
陌清茗
陌清茗 2021-01-01 21:40

I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have [\"Alpha\", \"Beta\", \"Gamma\"] and want to join

16条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 22:16

    The following is no longer language-agnostic (but that doesn't matter for the discussion because the implementation is easily portable to other languages). I tried to implement Luke's (theretically best) solution in an imperative programming language. Take your pick; mine's C#. Not very elegant at all. However, (without any testing whatsoever) I could imagine that its performance is quite decent because the recursion is in fact tail recursive.

    My challenge: give a better recursive implementation (in an imperative language). You say what “better” means: less code, faster, I'm open for suggestions.

    private static StringBuilder RecJoin(IEnumerator xs, string sep, StringBuilder result) {
        result.Append(xs.Current);
        if (xs.MoveNext()) {
            result.Append(sep);
            return RecJoin(xs, sep, result);
        } else
            return result;
    }
    
    public static string Join(this IEnumerable xs, string separator) {
        var i = xs.GetEnumerator();
        if (!i.MoveNext())
            return string.Empty;
        else
            return RecJoin(i, separator, new StringBuilder()).ToString();
    }
    

提交回复
热议问题