The standard library in C language lacks the trim () function for string operations, which is inconvenient to use. You can use strlen, isspace functions, and pointers to write one by yourself.
1. strlen Function
Prototype: extern int strlen (char * s );
Usage: # include <string. h>
Function: calculates the length of string S.
Description: return the length of S, excluding the terminator null.
2. isspace Functions
Prototype: extern int isspace (int c );
Usage: # include <ctype. h>
Function: determines whether character C is a blank character.
NOTE: If "C" is a blank character, a non-zero value is returned. Otherwise, zero is returned.
Blank spaces refer to spaces, horizontal tabulation, vertical tabulation, form feed, carriage return, and line feed.
3. Trim Functions
# Include <string. h>
# Include <ctype. h>
Char * trim (char * Str)
{
Char * P = STR;
Char * P1;
If (P)
{
P1 = P + strlen (STR)-1;
While (* P & isspace (* p) P ++;
While (P1> P & isspace (* P1) * P1 -- = '\ 0 ';
}
Return P;
}
4. Application Example
Int main ()
{
Int I = 0;
Char STRs [] [1, 128] = {
Null,
"",
"",
"Hello world ",
"Hello ",
"Hello world ",
"Hello world ",
"\ T \ n \ thello world ",
"End"
};
Do
{
Printf ("Trim (\" % s \ ") = % S. \ n", STRs [I], trim (STRs [I]);
} While (strcmp (STRs [I ++], "end "));
Return 0;
}