分隔符代码修订

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
/*
int main(void)
{
	char str[] = "root:x::0:root:/root:/bin/bash:";
	char *token;


	token = strtok(str, ":");
	printf("%s\n", token);
	while ( (token = strtok(NULL, ":")) != NULL)
		printf("%s\n", token);
	
	return 0;
}*/
char aa[32];
char *split_data( char *init_data, char *separator,int num)
{
char str[] = "root:x:0:root:/root:/bin/bash:";
	char *token=NULL;
	char p[128];//慎用指针,之前在此用的是指针,然后一直出错,换成数组就可以了!
	int j=0;
	strcpy(p,init_data);	
//	p=init_data;
	//token = strtok(&init_data,&separator);
	token = strtok(p, separator);
//	printf("%s\n", token);
	for(int i=0;i<num;i++)
	{
	// if( (token = strtok(NULL, separator)) != NULL)
		//printf("%s\n", token);
		token = strtok(NULL, separator);
		j++;
	}
	//printf("%s\n", token);
	strcpy(aa,token);
	
        return aa;
}

void main(void)
{
	char str[] = "root:x:0:root:/root:/bin/bash:";
	char str1[] = "root";
	char a[32];
	char b[32];
	char c[32];
	char d[32];
	char e[32];
	char f[32];

	int w=0;
	int num=3,j=0;
	w=sizeof(str1);
	printf("%d\n", w);
   strcpy(a,split_data( str1,",",2));
   printf("%s\n", a);

   strcpy(b,split_data( str1,",",3));
   printf("%s\n", b);

   strcpy(c,split_data( str1,",",4));
   printf("%s\n", c);

   strcpy(d,split_data( str1,",",5));
   printf("%s\n", d);

   strcpy(e,split_data( str1,",",6));
   printf("%s\n", e);

   strcpy(f,split_data( str1,",",7));
   printf("%s\n", f);


}

你可能感兴趣的:(分隔符代码修订)