String joining function in C The 2019 Stack Overflow Developer Survey Results Are InMaking a function which takes char* exception-proofgetline substitute that will enforce 'n' as limit of characters readAdding support to Busybox vi for reading file from stdinLow level string manipulation functions in CString “Contains” char functionCreating index to a file in CSplitting a UTF-8 string into equal-sized byte-arrays for parallel processingLex simple line-counting grammarFunction to scan input to string buffer in CEnforcing string validity with the C# type system

How was Skylab's orbit inclination chosen?

How to deal with fear of taking dependencies

Extreme, unacceptable situation and I can't attend work tomorrow morning

Inflated grade on resume at previous job, might former employer tell new employer?

Lethal sonic weapons

Is flight data recorder erased after every flight?

What are the motivations for publishing new editions of an existing textbook, beyond new discoveries in a field?

"To split hairs" vs "To be pedantic"

How can I fix this gap between bookcases I made?

Inversion Puzzle

Unbreakable Formation vs. Cry of the Carnarium

The difference between dialogue marks

Why is it "Tumoren" and not "Tumore"?

Is it possible for the two major parties in the UK to form a coalition with each other instead of a much smaller party?

Output the Arecibo Message

Should I use my personal or workplace e-mail when registering to external websites for work purpose?

What is the meaning of Triage in Cybersec world?

Where to refill my bottle in India?

What is the use of option -o in the useradd command?

Inline version of a function returns different value then non-inline version

If Wish Duplicates Simulacrum, Are Existing Duplicates Destroyed?

Is bread bad for ducks?

Poison Arrows Piercing damage reduced to 0, do you still get poisoned?

Why don't Unix/Linux systems traverse through directories until they find the required version of a linked library?



String joining function in C



The 2019 Stack Overflow Developer Survey Results Are InMaking a function which takes char* exception-proofgetline substitute that will enforce 'n' as limit of characters readAdding support to Busybox vi for reading file from stdinLow level string manipulation functions in CString “Contains” char functionCreating index to a file in CSplitting a UTF-8 string into equal-sized byte-arrays for parallel processingLex simple line-counting grammarFunction to scan input to string buffer in CEnforcing string validity with the C# type system



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0












$begingroup$


I wrote a function that joins a collection of Strings with a delimiter. It's based on Java's version of the function. I'm assuming C has some similar built-in.



Example:



int main() 
char* coll[] = "Hello", "World", "This", "Should", "Be", "Joined!";
char* joined = awfulJoinStr(", ", coll, 6);

printf("%sn", joined);
// Prints "Hello, World, This, Should, Be, Joined!"



Basically how it works is, it alternates between iterating the collection strings and the delimiter. It writes the current word to the buffer until it hits a null terminator, then it switches to either writing the next word, or to the delimiter.



I'm new to C, so I'd like comments on anything in the code. My main concerns:



  • It's super inefficient. All the strings need to be iterated at the start to get a total length so I know how big of a buffer to allocate later. I can't see how else I'd do it though unless I do reallocation while writing, but that seems like it would be even more inefficient.


  • It requires three iteration counters (stringI, charI, and bufferI) and a flag. I need to keep track of the current word that I'm writing, my position in it, and need to track where I am in the buffer. I also need a flag to track when I'm currently writing a delimiter or word.


  • It requires passing in how many strings I want to join (nStrings). This seems like it's necessary as well since I can't know the length of strArr, but it's unfortunate.


  • It's huge. It doesn't fit in one screen at a comfortable zoom.


I also included my version of strlen for kicks, and because I used it instead of the built-in.



#include <stdlib.h>
#include <stdbool.h>

size_t myStrLen(char* str)
size_t length = 0;

while (str[length] != '')
length++;


return length;


char* awfulJoinStr(char* delimiter, char** strArr, size_t nStrings)
size_t delimiterSize = myStrLen(delimiter);
size_t totalDelimiterSize = (nStrings - 1) * delimiterSize;

size_t totalStringSize = 0;
for (size_t i = 0; i < nStrings; i++)
totalStringSize += myStrLen(strArr[i]);


size_t bufferSize = totalDelimiterSize + totalStringSize + 1;
char* buffer = malloc(sizeof(char) * bufferSize);
buffer[bufferSize - 1] = '';

bool inDelim = false;
size_t charI = 0;
size_t stringI = 0;
for (size_t bufferI = 0; bufferI < bufferSize - 1;)
char current = inDelim ? delimiter[charI] : strArr[stringI][charI];

if (current == '')
// Start at the beginning of the word and toggle what we're writing
charI = 0;

if (!inDelim)
stringI++;


inDelim = !inDelim;

else
buffer[bufferI] = current;

charI++;
bufferI++;



return buffer;









share









$endgroup$


















    0












    $begingroup$


    I wrote a function that joins a collection of Strings with a delimiter. It's based on Java's version of the function. I'm assuming C has some similar built-in.



    Example:



    int main() 
    char* coll[] = "Hello", "World", "This", "Should", "Be", "Joined!";
    char* joined = awfulJoinStr(", ", coll, 6);

    printf("%sn", joined);
    // Prints "Hello, World, This, Should, Be, Joined!"



    Basically how it works is, it alternates between iterating the collection strings and the delimiter. It writes the current word to the buffer until it hits a null terminator, then it switches to either writing the next word, or to the delimiter.



    I'm new to C, so I'd like comments on anything in the code. My main concerns:



    • It's super inefficient. All the strings need to be iterated at the start to get a total length so I know how big of a buffer to allocate later. I can't see how else I'd do it though unless I do reallocation while writing, but that seems like it would be even more inefficient.


    • It requires three iteration counters (stringI, charI, and bufferI) and a flag. I need to keep track of the current word that I'm writing, my position in it, and need to track where I am in the buffer. I also need a flag to track when I'm currently writing a delimiter or word.


    • It requires passing in how many strings I want to join (nStrings). This seems like it's necessary as well since I can't know the length of strArr, but it's unfortunate.


    • It's huge. It doesn't fit in one screen at a comfortable zoom.


    I also included my version of strlen for kicks, and because I used it instead of the built-in.



    #include <stdlib.h>
    #include <stdbool.h>

    size_t myStrLen(char* str)
    size_t length = 0;

    while (str[length] != '')
    length++;


    return length;


    char* awfulJoinStr(char* delimiter, char** strArr, size_t nStrings)
    size_t delimiterSize = myStrLen(delimiter);
    size_t totalDelimiterSize = (nStrings - 1) * delimiterSize;

    size_t totalStringSize = 0;
    for (size_t i = 0; i < nStrings; i++)
    totalStringSize += myStrLen(strArr[i]);


    size_t bufferSize = totalDelimiterSize + totalStringSize + 1;
    char* buffer = malloc(sizeof(char) * bufferSize);
    buffer[bufferSize - 1] = '';

    bool inDelim = false;
    size_t charI = 0;
    size_t stringI = 0;
    for (size_t bufferI = 0; bufferI < bufferSize - 1;)
    char current = inDelim ? delimiter[charI] : strArr[stringI][charI];

    if (current == '')
    // Start at the beginning of the word and toggle what we're writing
    charI = 0;

    if (!inDelim)
    stringI++;


    inDelim = !inDelim;

    else
    buffer[bufferI] = current;

    charI++;
    bufferI++;



    return buffer;









    share









    $endgroup$














      0












      0








      0





      $begingroup$


      I wrote a function that joins a collection of Strings with a delimiter. It's based on Java's version of the function. I'm assuming C has some similar built-in.



      Example:



      int main() 
      char* coll[] = "Hello", "World", "This", "Should", "Be", "Joined!";
      char* joined = awfulJoinStr(", ", coll, 6);

      printf("%sn", joined);
      // Prints "Hello, World, This, Should, Be, Joined!"



      Basically how it works is, it alternates between iterating the collection strings and the delimiter. It writes the current word to the buffer until it hits a null terminator, then it switches to either writing the next word, or to the delimiter.



      I'm new to C, so I'd like comments on anything in the code. My main concerns:



      • It's super inefficient. All the strings need to be iterated at the start to get a total length so I know how big of a buffer to allocate later. I can't see how else I'd do it though unless I do reallocation while writing, but that seems like it would be even more inefficient.


      • It requires three iteration counters (stringI, charI, and bufferI) and a flag. I need to keep track of the current word that I'm writing, my position in it, and need to track where I am in the buffer. I also need a flag to track when I'm currently writing a delimiter or word.


      • It requires passing in how many strings I want to join (nStrings). This seems like it's necessary as well since I can't know the length of strArr, but it's unfortunate.


      • It's huge. It doesn't fit in one screen at a comfortable zoom.


      I also included my version of strlen for kicks, and because I used it instead of the built-in.



      #include <stdlib.h>
      #include <stdbool.h>

      size_t myStrLen(char* str)
      size_t length = 0;

      while (str[length] != '')
      length++;


      return length;


      char* awfulJoinStr(char* delimiter, char** strArr, size_t nStrings)
      size_t delimiterSize = myStrLen(delimiter);
      size_t totalDelimiterSize = (nStrings - 1) * delimiterSize;

      size_t totalStringSize = 0;
      for (size_t i = 0; i < nStrings; i++)
      totalStringSize += myStrLen(strArr[i]);


      size_t bufferSize = totalDelimiterSize + totalStringSize + 1;
      char* buffer = malloc(sizeof(char) * bufferSize);
      buffer[bufferSize - 1] = '';

      bool inDelim = false;
      size_t charI = 0;
      size_t stringI = 0;
      for (size_t bufferI = 0; bufferI < bufferSize - 1;)
      char current = inDelim ? delimiter[charI] : strArr[stringI][charI];

      if (current == '')
      // Start at the beginning of the word and toggle what we're writing
      charI = 0;

      if (!inDelim)
      stringI++;


      inDelim = !inDelim;

      else
      buffer[bufferI] = current;

      charI++;
      bufferI++;



      return buffer;









      share









      $endgroup$




      I wrote a function that joins a collection of Strings with a delimiter. It's based on Java's version of the function. I'm assuming C has some similar built-in.



      Example:



      int main() 
      char* coll[] = "Hello", "World", "This", "Should", "Be", "Joined!";
      char* joined = awfulJoinStr(", ", coll, 6);

      printf("%sn", joined);
      // Prints "Hello, World, This, Should, Be, Joined!"



      Basically how it works is, it alternates between iterating the collection strings and the delimiter. It writes the current word to the buffer until it hits a null terminator, then it switches to either writing the next word, or to the delimiter.



      I'm new to C, so I'd like comments on anything in the code. My main concerns:



      • It's super inefficient. All the strings need to be iterated at the start to get a total length so I know how big of a buffer to allocate later. I can't see how else I'd do it though unless I do reallocation while writing, but that seems like it would be even more inefficient.


      • It requires three iteration counters (stringI, charI, and bufferI) and a flag. I need to keep track of the current word that I'm writing, my position in it, and need to track where I am in the buffer. I also need a flag to track when I'm currently writing a delimiter or word.


      • It requires passing in how many strings I want to join (nStrings). This seems like it's necessary as well since I can't know the length of strArr, but it's unfortunate.


      • It's huge. It doesn't fit in one screen at a comfortable zoom.


      I also included my version of strlen for kicks, and because I used it instead of the built-in.



      #include <stdlib.h>
      #include <stdbool.h>

      size_t myStrLen(char* str)
      size_t length = 0;

      while (str[length] != '')
      length++;


      return length;


      char* awfulJoinStr(char* delimiter, char** strArr, size_t nStrings)
      size_t delimiterSize = myStrLen(delimiter);
      size_t totalDelimiterSize = (nStrings - 1) * delimiterSize;

      size_t totalStringSize = 0;
      for (size_t i = 0; i < nStrings; i++)
      totalStringSize += myStrLen(strArr[i]);


      size_t bufferSize = totalDelimiterSize + totalStringSize + 1;
      char* buffer = malloc(sizeof(char) * bufferSize);
      buffer[bufferSize - 1] = '';

      bool inDelim = false;
      size_t charI = 0;
      size_t stringI = 0;
      for (size_t bufferI = 0; bufferI < bufferSize - 1;)
      char current = inDelim ? delimiter[charI] : strArr[stringI][charI];

      if (current == '')
      // Start at the beginning of the word and toggle what we're writing
      charI = 0;

      if (!inDelim)
      stringI++;


      inDelim = !inDelim;

      else
      buffer[bufferI] = current;

      charI++;
      bufferI++;



      return buffer;







      beginner c strings c99





      share












      share










      share



      share










      asked 2 mins ago









      CarcigenicateCarcigenicate

      3,89511632




      3,89511632




















          0






          active

          oldest

          votes












          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217163%2fstring-joining-function-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217163%2fstring-joining-function-in-c%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订