#define LTRIM(s) trim(s,1) #define RTRIM(s) trim(s,2) #define TRIM(s) trim(s,0) /* This function remove all white spaces from the right and left end of a string INPUT str : string to analize INPUT mode: possible value -> 0,3: Remove all white spaces from the right and left end of a string 1 : Remove all white spaces from the left string 2 : Remove all white spaces from the right string RETURN 0 : for empthy string otherwise 1 */ char trim(char* str,char mode) { char *s,*p; char *sp,*ep; if (strlen(str)==0)//empty string return 0; s= malloc(strlen(str));//reserve area s=str;// copy string to new area p=s; if (!mode) mode=3;//complete trim if (mode & 1) { while(isspace(*p))//left trim p++; } sp=p; if (mode & 2) { p=p+strlen(p); p--; while(isspace(*p))//right trim p--; p++; *p=0;//null char to end string } strcpy(str,sp);//update new string free(s);//free memory return 1; } void Testfunction() { char strm[50]; sprintf(strm," Hello World "); printf("Start len:%d string <%s> \n",strlen(strm),strm); LTRIM(strm); printf("Ltrim len:%d string <%s>\n",strlen(strm),strm); RTRIM(strm); printf("Rtrim len:%d string <%s> \n",strlen(strm),strm); sprintf(strm," Hello World "); TRIM(strm); printf("TRIM len:%d string <%s> \n",strlen(strm),strm); return; }
Advertisements
Leave a Reply