c实现字符串拆分与提取

#include <stdio.h>
#include <string.h>

/*
源字符串: dads{ORG}sadasdsa{一些公式}asdasds{ORG}sadsadsa{一些公式}dsadasd...........

  1.  S0001,ORG1,AIM0001,S0002,ORG2,S0003,AIM0002,S0004.........
  2.  dads,ORG,sadasdsa,0,asdasds,ORG,sadsadsa,0,dsadasd......
  3. S0001 || ORG1 || AIM0001 ||S0002 || ORG2 || S0003 || AIM0002 || S0004 ......
  
	拆成以下三种拼接字符串
	
	  字符串 搞的多呀
	  { } 以外的 用 S000n 表示
	  {ORG} 用 ORGn 表示
	  {一些公式} 用 AIM000n 表示
	  
		第二个特殊点,{一些公式} 全变成 0 了

*/

#define MAX_NUM 4096
#define MAX_STR_NUM 30
#define STR_NUM 256

enum
{
	STR_NULL=0,
	STR_LEFT,
	STR_MID,
	STR_RIGHT
};

typedef struct stStr
{
	char str[STR_NUM];
	unsigned int uiID;
	unsigned int uiCnt;
} ST_STR;

int main()
{
	char* str = "adads{ORG}bsadasdsa{SOMETHING}casdasds{ORG}dsadsadsa{SOMETHING}edsadasd";
	char str_L_before[MAX_NUM] = {0};
	char str_L_after[MAX_NUM] = {0};
	char str_R_before[MAX_NUM] = {0};
	char str_R_after[MAX_NUM] = {0};//字符数组最好用链表或动态数组来实现,这里时间关系先这样吧

	char str_tmp[MAX_NUM] = {0};
	char str_all[MAX_STR_NUM][MAX_NUM] = {{0}};
	ST_STR st_str_arr[MAX_STR_NUM] = {{0},STR_NULL,0};


	
	unsigned int i = 0;
	unsigned int n = 0;
	unsigned int m = 0;

	unsigned int ui_str_1 = 0;
	unsigned int ui_str_2 = 0;
	unsigned int ui_str_3 = 0;
	unsigned int ui_str_4 = 0;
	
	char* p = str;

	for (i=0;i<strlen(p);i++)
	{
		char str_tmp[MAX_NUM] = {0};
		
		printf("-------------%c %d\n",p[i],i);

		if ('{' == p[i])
		{
			strncpy(str_L_before,p,i);
			printf("%s\n",str_L_before); //{前的字符串
			strncpy(str_all[n++],str_L_before,i);
			strncpy(st_str_arr[st_str_arr->uiCnt].str,str_L_before,i);
			st_str_arr[st_str_arr->uiCnt].uiID = STR_LEFT;
			st_str_arr->uiCnt++;
			p = p+i+1;
			//printf("%s\n",str);
			i = 0;
			continue;
		}
		else if ('}' == p[i])
		{
			strncpy(str_L_after,p,i);
			printf("%s\n",str_L_after); //{}间的字符串
			strncpy(str_all[n++],str_L_after,i);
			strncpy(st_str_arr[st_str_arr->uiCnt].str,str_L_after,i);
			st_str_arr[st_str_arr->uiCnt].uiID = STR_MID;
			st_str_arr->uiCnt++;
			p = p+i+1;
			//printf("%s\n",str);
			
			strcpy(str_R_after,p); //}后的字符串
			printf("================[%s]\n",str_R_after);

			i = 0;
			continue;
		}
	}

	//将最后剩下的拷贝到数组中去
	//strncpy(str_all[n++],str_R_after,strlen(str_R_after));
	strncpy(st_str_arr[st_str_arr->uiCnt].str,str_R_after,strlen(str_R_after));
	st_str_arr[st_str_arr->uiCnt].uiID = STR_RIGHT;


	for (m=0;m<MAX_STR_NUM;m++)
	{
		char * p = st_str_arr[m].str;
		switch(st_str_arr[m].uiID)
		{
		case STR_LEFT:
		case STR_RIGHT:
			sprintf(str_tmp,"%ss000%d ",str_tmp,ui_str_1++);
			break;
		case STR_MID:
			if (!strcmp("ORG",p))
			{
				//ORGn表示
				sprintf(str_tmp,"%s%s%d ",str_tmp,p,ui_str_2++);
			}
			else
			{
				//AIM000n表示
				sprintf(str_tmp,"%sAIM000%d ",str_tmp,ui_str_3++);
			}
			break;
		default:
			break;
		}
	}

	printf("%s\n",str_tmp);

	return 0;
}

你可能感兴趣的:(c实现字符串拆分与提取)