Last active
September 5, 2024 22:24
-
-
Save gustavorv86/c5fe4f279258ac0cfcebad88bb6acee2 to your computer and use it in GitHub Desktop.
Split a string (char*) by a character in C/C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
void string_split(char * string, char sep, char *** r_array_string, int * r_size) { | |
int i, k, len, size; | |
char ** array_string; | |
// Number of substrings | |
size = 1, len = strlen(string); | |
for(i = 0; i < len; i++) { | |
if(string[i] == sep) { | |
size++; | |
} | |
} | |
array_string = malloc(size * sizeof(char*)); | |
i=0, k=0; | |
array_string[k++] = string; // Save the first substring pointer | |
// Split 'string' into substrings with \0 character | |
while(k < size) { | |
if(string[i++] == sep) { | |
string[i-1] = '\0'; // Set end of substring | |
array_string[k++] = (string+i); // Save the next substring pointer | |
} | |
} | |
*r_array_string = array_string; | |
*r_size = size; | |
return; | |
} | |
int main() { | |
char string[] = "parse,this,string,with,the,comma,separator"; | |
char ** array_string; | |
int i, size; | |
string_split(string, ',', &array_string, &size); | |
printf("Number of substrings: %d \n", size); | |
for(i = 0; i < size; i++) { | |
printf("%d: %s \n", i, array_string[i]); | |
} | |
free(array_string); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment