I have a char array in string of the format <item1>:<item2>:<item3> what is the best way to break it down so that I can print the different items separately? Should I just loop through the array, or is there some string function that can help?
4 Answers
You can try strtok: here is some sample code to get the sub string which is separated by , - or |
#include <stdio.h>
#include <string.h>
int main(int argc,char **argv)
{
char buf1[64]={'a', 'a', 'a', ',' , ',', 'b', 'b', 'b', '-', 'c','e', '|', 'a','b', };
/* Establish string and get the first token: */
char* token = strtok( buf1, ",-|");
while( token != NULL )
{
/* While there are tokens in "string" */
printf( "%s ", token );
/* Get next token: */
token = strtok( NULL, ",-|");
}
return 0;
}
2 Comments
Simply iterate over the string and everytime you hit ':', print whatever has been read since the last occurrence of ':'.
#define DELIM ':'
char *start, *end;
start = end = buf1;
while (*end) {
switch (*end) {
case DELIM:
*end = '\0';
puts(start);
start = end+1;
*end = DELIM;
break;
case '\0':
puts(start);
goto cleanup;
break;
}
end++;
}
cleanup:
// ...and get rid of gotos ;)
sscanf()orstrtok()or do it your implementation isn't hard..