The test code is as follows:
# Include <stdio. h>
# Include <stdlib. h>
Char * trim (char * Str );
Int main (INT argc, char * argv [])
{
Char str1 [] = "";
Char str2 [] = "\ 0 ";
Char str3 [] = "ABC def Ghi ";
Trim (str1 );
Printf ("[% s] \ n", str1 );
Trim (str2 );
Printf ("[% s] \ n", str2 );
Trim (str3 );
Printf ("[% s] \ n", str3 );
System ("pause ");
Return 0;
}
/*
The character pointer variable t points to the last character of the string,
If the value of T is a space and the address of T is greater than S, the value of T's address is set to the end of the string,
Then, the T address is reduced;
Point the character pointer variable F to the first non-space position of the string, and forward the character after F;
*/
Void trim (char * s)
{
Char * t = S + strlen (S)-1;
Char * f = s;
Int itemp = 0;
While (isspace (* t) | isspace (* F ))
{
If (T> = S & isspace (* t ))
{
* T = '\ 0 ';
-- T;
}
If (F <= T & isspace (* F) f ++;
}
While (F <= T)
{
* (S + itemp) = (* F );
++ Itemp;
++ F;
}
* (S + itemp) = '\ 0 ';
}
Test environment of the program:
Winxpsp2, Dev C ++ 4.9.9.2