Algorithm for joining e.g. an array of strings

后端 未结 16 1878
陌清茗
陌清茗 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:10

    In Perl, I just use the join command:

    $ echo "Alpha
    Beta
    Gamma" | perl -e 'print(join(", ", map {chomp; $_} <> ))'
    Alpha, Beta, Gamma
    

    (The map stuff is mostly there to create a list.)

    In languages that don't have a built in, like C, I use simple iteration (untested):

    for (i = 0; i < N-1; i++){
        strcat(s, a[i]);
        strcat(s, ", ");
    }
    strcat(s, a[N]);
    

    Of course, you'd need to check the size of s before you add more bytes to it.

    You either have to special case the first entry or the last.

提交回复
热议问题