How to get an array from this line?
so i have the following li开发者_运维技巧ne
BOOK_NAME_VALUE STRING Programming
i need to make an array contain this
a[0] = "BOOK_NAME";
a[1] = "VALUE";
a[2] = "STRING";
a[3] = "Programming";
the 2nd value of the array is the last part of the 1st part of the line; the line separator is white space ' ' the 1st part separator is '_'
so any idea ??
UPDATE
i did this for the 2nd separation process,, need shorter way ??
#include<string.h>
char **str_tok(char *str,char* d){
char *out[2];
char *s;
char *c;
int toks = noToks(str,d);
int i = 0;
s = strtok(str,d);
i++;
while(i != toks){
strcat(s, d);
c = strtok(NULL,d);
i++;
strcat(s,c);
}
strcpy(out[0],s);
c = strtok(NULL,d);
strcpy(out[1], c);
return out;
}
int noToks(char *str,char *d){
int c = 0;
while(*str)
if(*str == *d){
c++;
str++;
}
return c;
}
Take a look at strtok
function, that is used to split strings according to a set of specified delimiters.
Read here to find the documentation of the function and some examples.. basically you call
char *cur = strtok(your_string," ");
to obtain the first string and then you can keep calling the function with a NULL
argument to obtain successive pieces:
while (cur != NULL) {
// do whatever
cur = strtok(NULL," ");
}
First split the string by spaces, which will give three strings (array).
Then simply find the last '_' in the first string in the strings array from above.
Combine all into a new array.
I'd put some code but this is terribly simple and if you're learning C then I suggest look for the functions yourself. I gave you the direction.
Hope it helps.
精彩评论