#include #include #include /** * @brief Function to split a string into an array of strings * * @details This function splits a string into an array of strings using a * delimiter character. The function allocates memory for the array of strings * and the individual strings. The caller is responsible for freeing the memory * allocated by this function. * * @param str The string to split * @param delimiter The character to split the string by * * @return An array of strings */ char **split_str(const char *str, char delimiter) { int count = 1; // Number of substrings (at least 1) for (int i = 0; str[i] != '\0'; i++) { // Count the number of delimiters until the end if (str[i] == delimiter) count++; } // clang-format off // Allocate memory for the array of strings (+1 for NULL terminator) // Code format for those who don't know: // | (char **) for casting, something C++ already does (we love C) // | malloc for allocating memory // | (count + 1) * sizeof(char *) for the size of the array of strings // | now for the memory size, since we previously counted the number of // | delimiters we can use that to allocate the memory for the strings char **result = (char **)malloc((count + 1) * sizeof(char *)); if (!result) return NULL; // In case there is not enough memory // let's get real: string will be " /IAE/ /CHALLENGE/" (space at first too) int start = 0, pos = 0; int len = strlen(str); // Length of the string: 18 for (int i = 0; i <= len; i++) { // Loop through the string if (str[i] == delimiter || str[i] == '\0') { // Found a delimiter or end of string (that would be "/") int word_length = i - start; // Length of the word, in this case 1 result[pos] = (char *)malloc( (word_length + 1) * sizeof(char)); // Allocate memory for the word, // size would be 1 + char size if (!result[pos]) { // Free previously allocated memory in case of failure for (int j = 0; j < pos; j++) { free(result[j]); } free(result); return NULL; } strncpy(result[pos], &str[start], word_length); // Copy the string from start to word_length result[pos][word_length] = '\0'; // Null terminate pos++; start = i + 1; } } // clang-format on result[pos] = NULL; // Null terminate the array of strings return result; // Return the array of strings } int main(void) { printf("--------[BONUS]--------"); char *str = " /IAE/ /CHALLENGE/"; // Change this to test with different strings char **vector = split_str(str, '/'); int i; i = 0; while (vector[i] != NULL) { printf("Substring %d : %s\n", i + 1, vector[i]); i++; } while (vector[i] != NULL) { free(vector[i]); i++; } free(vector); return (0); }