* @brief Splits a String object into an array of String objects based on a specified delimiter. * * This function takes a String object and splits it into multiple String objects using the specified delimiter. * The result is an array of String pointers, and the number of resulting splits is stored in the count parameter. * If the input String object, delimiter, or memory allocation fails, the
| 2251 | * @return An array of String pointers containing the split strings, or NULL if an error occurs. |
| 2252 | */ |
| 2253 | String** string_split(const String *str, const char *delimiter, int *count) { |
| 2254 | STRING_LOG("[string_split]: Function start."); |
| 2255 | |
| 2256 | if (str == NULL) { |
| 2257 | STRING_LOG("[string_split]: Error - Null String object."); |
| 2258 | return NULL; |
| 2259 | } |
| 2260 | if (delimiter == NULL) { |
| 2261 | STRING_LOG("[string_split]: Error - Null delimiter."); |
| 2262 | return NULL; |
| 2263 | } |
| 2264 | |
| 2265 | size_t num_splits = 0; |
| 2266 | char *temp = string_strdup(str->dataStr); |
| 2267 | if (temp == NULL) { |
| 2268 | STRING_LOG("[string_split]: Error - Memory allocation failed."); |
| 2269 | return NULL; |
| 2270 | } |
| 2271 | |
| 2272 | char *token = strtok(temp, delimiter); |
| 2273 | |
| 2274 | while (token != NULL) { |
| 2275 | num_splits++; |
| 2276 | token = strtok(NULL, delimiter); |
| 2277 | } |
| 2278 | free(temp); |
| 2279 | |
| 2280 | if (num_splits == 0) { |
| 2281 | STRING_LOG("[string_split]: No splits found."); |
| 2282 | return NULL; |
| 2283 | } |
| 2284 | |
| 2285 | String **splits = (String**)malloc(sizeof(String*) * num_splits); |
| 2286 | if (splits == NULL) { |
| 2287 | STRING_LOG("[string_split]: Error - Memory allocation failed for splits array."); |
| 2288 | return NULL; |
| 2289 | } |
| 2290 | |
| 2291 | temp = string_strdup(str->dataStr); |
| 2292 | if (temp == NULL) { |
| 2293 | STRING_LOG("[string_split]: Error - Memory allocation failed."); |
| 2294 | free(splits); |
| 2295 | return NULL; |
| 2296 | } |
| 2297 | |
| 2298 | token = strtok(temp, delimiter); |
| 2299 | size_t index = 0; |
| 2300 | |
| 2301 | while (token != NULL && index < num_splits) { |
| 2302 | splits[index] = string_create(token); |
| 2303 | if (splits[index] == NULL) { |
| 2304 | STRING_LOG("[string_split]: Error - Failed to create string at index %zu.", index); |
| 2305 | // Free previously allocated strings and array |
| 2306 | for (size_t i = 0; i < index; i++) { |
| 2307 | string_deallocate(splits[i]); |
| 2308 | } |
| 2309 | free(splits); |
| 2310 | free(temp); |
nothing calls this directly
no test coverage detected