70,024
社区成员




#include <stdio.h>
#include <string.h>
int main(void)
{
char headinfo[4096];
char seps1[] = ";";
char seps2[] = ",;";
char *token1;
char *token2;
strcpy(headinfo, "field1,100,0;field2,80,1;field3,120,2");
token1 = strtok(headinfo, seps1);
while (token1 != NULL)
{
/* While there are tokens in headinfo */
printf("%s\n", token1);
/* Get next token: */
token1 = strtok(NULL, seps1);
}
strcpy(headinfo, "field1,100,0;field2,80,1;field3,120,2"); /*strtok modofy headinfo, so recopy*/
token2 = strtok(headinfo, seps2);
while (token2 != NULL)
{
/* While there are tokens in iteminfo */
printf("%s\n", token2);
/* Get next token: */
token2 = strtok(NULL, seps2);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[1000];
char ss[50][50];
gets(str);
int j = 0,k = 0;
unsigned int i = 0;
for( i = 0;i < strlen(str); ++i )
{
if( str[i] == ' ' || str[i] == '\t' || str[i] == '\b' )
{
ss[k][j] = '\0';
j = 0;
k++;
}
else
{
ss[k][j++] = str[i];
}
}
ss[k][j] = '\0';
for( int m = 0; m <= k; ++m )
{
printf("%s\n",ss[m]);
}
return 0;
}
/*
* split a string into words, must free after use
*/
int str_split(char ***words, const char *line, char delim) {
int word_counter = str_count_char(line, delim) + 1;
*words = (char **) malloc(sizeof(char *) * word_counter);
int i = 0;
char *p = line;
while ( 1 ) {
char *s = p;
p = strchr(p, delim);
int len = ( p ) ? p - s : strlen(s);
(*words)[i] = (char *) malloc(sizeof(char) * (len + 1));
strncpy((*words)[i], s, len);
(*words)[i][len] = 0;
if ( !p ) break;
p++;
i++;
}
return word_counter;
}
void test_str_split(){
printf("\n\n<%d>str_split() test:\n", Counter ++);
char **words;
char line[] = "Hello! How are you? Fine. Thank you!";
char delim = ' ';
int i = 0, j = 0;
int word_counter = str_split(&words, line, delim);
printf(" line: %s", line);
for(i=0; i<word_counter; i++){
printf("\n words[%d]: ",i);
j = 0;
while(words[i][j] != '\0'){
printf("%c", words[i][j++]);
}
free(words[i]);
}
free(words);
}
//这行字符串比如是test,有空格也可能有tab键,只要有空格或者tab都要分隔开,然后把分隔开的每组字符串放到p[]数组中。
#include <stdio.h>
#include <string.h>
char test[4096];
char p[100][21];//最多保存100个token,每个token不超过20个字符
int n,i;
char seps[] = " \t";
char *token;
int main(void)
{
strcpy(test, "field1234567890123456789 100\t0 field2\t\t80\t \t1 field3 120 2");
n=0;
token = strtok(test, seps);
while (token != NULL)
{
printf("%s\n", token);
strncpy(p[n],token,20);p[n][20]=0;//忽略20个以后的字符
n++;
if (n>=100) break;//忽略100个以后的token
token = strtok(NULL, seps);
}
for (i=0;i<1;i++) {
printf("%d [%s]\n",i+1,p[i]);
}
return 0;
}