1 #define _CRT_SECURE_NO_WARNINGS 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 6 7 int trimSpace(char *inbuf, char *outbuf) 8 { 9 char *tmpBuf = inbuf; 10 11 while(*tmpBuf!='\0') 12 { 13 if ((*tmpBuf) != ' ') 14 15 *outbuf++ = *tmpBuf; 16 } 17 tmpBuf++; 18 } 19 *outbuf = '\0'; 20 } 21 int main() 22 { 23 char *inbuf; 24 char *outbuf = NULL; 25 outbuf =(char *)malloc(100); 26 inbuf = " abcdefg "; 27 28 trimSpace(inbuf, outbuf); 29 printf("trimSpace後outbuf:%s\n", outbuf); 30 system("pause"); 31 return 0; 32 }
去除兩端的空格(兩頭堵):
1 #define _CRT_SECURE_NO_WARNINGS 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 6 void getCount2(char *str, int *pCount) 7 { 8 int nCount = 0; 9 char *p = str; 10 int i, j = 0; 11 i = 0; 12 j = strlen(str)-1; 13 14 if (str == NULL) 15 { 16 return -1; 17 } 18 while (isspace(p[i])&&p[i]!='\0') 19 { 20 i++; 21 } 22 while (isspace(p[j]) && p[j] != '\0') 23 { 24 j--; 25 } 26 27 nCount = j - i + 1; 28 *pCount = nCount; 29 } 30 31 int main() 32 { 33 char *str =" abcdefg "; 34 int pCount =0; 35 getCount2(str, &pCount); 36 printf("字符串%s的長度為(不包括空格):%d\n",str,pCount); 37 system("pause"); 38 return 0; 39 }