Hi CBuild,
I have written code similar to this before. It may not be the best, but it may help and contribute to what you are looking for. I will simply write a function called parseString(char *, char[][], char); which simply takes the source string, finds your designated char or in this case, a space, and then it seperates them putting them into their own 2-Dimensional char[][].
Code:
#include <string.h>
#include <stdio.h>
int parseString(char *src, char dest[][64], char find);
int main () {
int i, total; // Loop (i), Total found (total)
char names[256]; // Dummy variable
char seperatedNames[16][64]; // 16 strings, with 64 bytes each
// String copy data
strcpy(names, "name1 name2 name3 name4 name5");
// Parse the string, and how many ' ' found
total = parseString(names, seperatedNames, ' ');
// Display
printf("With %i found and seperated\n\n", total);
for (i = 0; i < total; i++) {
printf("%s\n", seperatedNames[i]);
}
return 0;
}
int parseString(char *src, char dest[][64], char find) {
int b, l, j, z = 1; // For loops
int location[16] = {0}; // Location of string
char *pch; // Character position
pch = strchr(src, find); // Find character
if (pch == NULL) // Fail safe
return (0);
while (pch != NULL) {
location[z] = pch-src+1; // Record Location
pch = strchr(pch+1, find); // Find again where left off
z++; // Keep location incremented
}
location[z] = strlen(src); // Last position
/*
** Write data to new array per 'find' found
*/
for (l = 0; l < z; l++) {
b = 0; // Start write pos at 0
/*
** Copy designated bytes per array
*/
for (j = location[l]; j < location[l+1]; j++) {
dest[l][b] = src[j]; // Copy bytes to dest
b++; // Increment
}
dest[l][b] = '\0';
}
return (z); // How many 'find' found
}
Code 1.1: Parsing a string
Ok, for an explanation of parseString(), I decided to use a 2-D array instead of a char *[] because I didn't see a need to allocate memory for this small task. Now if course this will be handling large strings and unknown size array's I would recommend you to use malloc(), free(), etc...
I simply take the *src, search for find, and seperate the lines inserting the data into dest[][]. If you have any question, please feel free to ask, I put some comments in there so you knew what each step was about.
Hope this helps,
- Stack Overflow