Coding Practice: Day 1

Converting array of words to a sentence

Coding Practice: Day 1

Problem - codewars.com

Today I learned how to basically convert an array to a string in the form of a sentence.
Mainly in C, because I already knew how to do it in Python.

The problem is making an array like {"This", "is", "a", "sentence"} into a string like “This is a sentence”.

Here was my first attempt, which is way longer than what I ended up with:

alt text

Here is the main function:

alt text

And it ouputs: This is a sentence

This works well but it can be simplified to be more writable.
I found someone’s solution, which saved the sentence to a string using sprintf, which is fine because we know our math in calculating the buffer size is correct; however, I wanted to learn how to implement this using snprintf, the more secure version because it includes a buffer size to prevent buffer overflow.

Here’s my version of the code:

alt text

Apparently calloc(1, sizeof(1)) is the same as calloc(1, 1), but it’s self-documenting code, which I am trying to get better at.

In this case, my code might be over-documenting, but this is basically my writeup and I’m explaining in depth so it’s easier to understand later if I need to reference this.

This worked.

Here’s the Python implementation:
alt text

This prints: `hi there 3rdword"

If anyone is reading this, please let me know if you actually found this helpful, so I know whether to keep these as writeups for myself or detailed explanations.

Email copied to clipboard!
Discord username copied to clipboard!