Removes leading spaces and leading spaces from strings in C.
The string memory diagram is as follows:
Introduce header files:
1 #include<stdlib.h> 2 #include<stdio.h> 3 #include<string.h>
Function prototype:
1 void trim(char *strIn /*in*/, char *strOut /*in*/);
Implementation Method 1:
void trim(char *strIn, char *strOut){ int i, j ; i = 0; j = strlen(strIn) - 1; while(strIn[i] == ' ') ++i; while(strIn[j] == ' ') --j; strncpy(strOut, strIn + i , j - i + 1); strOut[j - i + 1] = '\0';}
Method 2:
1 void trim (char * strIn, char * strOut) {2 3 char * start, * end, * temp; // define the header and tail pointer of the string after spaces are removed and the traversal pointer 4 5 temp = strIn; 6 7 while (* temp = '') {8 ++ temp; 9} 10 11 start = temp; // obtain the header pointer 12 13 temp = strIn + strlen (strIn)-1; // obtain the pointer of the last character of the original string (not '\ 0') 14 15 printf ("% c \ n", * temp ); 16 17 while (* temp = '') {18 -- temp; 19} 20 21 end = temp; // obtain the tail pointer 22 23 24 for (strIn = start; strIn <= end;) {25 * strOut ++ = * strIn ++; 26} 27 28 * strOut = '\ 0'; 29}
Test:
1 void main(){ 2 char *strIn = " ak kl p "; 3 4 char strOut[100]; 5 6 trim(strIn, strOut); 7 8 printf("*%s*\n",strOut); 9 10 system("pause");11 }