C-Runtime Library: String trim Function
In the past, I always thought that the C Runtime Library does not contain functions such as string trim (in the code left by my predecessor, the big guys always write one by themselves :). In fact, in C runtime, there is a string trim function, that is, strspns!
Usage:
P = string1 + strspns (string1, "/t ");
Printf ("% s", P );
Char * string2 = "abcdefghijklmn <...> abcdefghijklmn ";
Printf ("% s", strpbrk (string2, "<> "));
Easy!
Strcspns, strpbrk, and strtok are all very useful functions. Unfortunately, I have not carefully read the C function reference manual before. So today I wrote a function that is exactly the same as the strspns function, i'm also proud of the skills I have used. Sweat!
In addition, C ++ STL: String supports the above functions, but the names are different. However, c99 and Ms do not support functions such as strrstr. You can only write one function by yourself!
By the way, the sscanf function is also very useful!
Today I have studied the implementation of strspns and strpbrk. The algorithms are really interesting. by imitating the code, I wrote the following two very convenient functions for my project:
Char * xstrpspn (const char * string, const char * end_ptr, const char * Control)
{
Const unsigned char * tail = (const unsigned char *) end_ptr;
Const unsigned char * STR = (const unsigned char *) string;
Const unsigned char * CTRL = (const unsigned char *) control;
Unsigned char map [32];
Int count;
Int backward;
// Clear out bit map
For (COUNT = 0; count <32; count ++ ){
Map [count] = 0;
}
// Set bits in control map
While (* CTRL ){
Map [* Ctrl> 3] | = (1 <(* CTRL & 7 ));
CTRL ++;
}
// 1st char not in control map stops search
If (* Str ){
Backward = (STR <= tail | null = tail )? 0: 1;
Count = 0;
While (STR! = Tail & (Map [* STR> 3] & (1 <(* STR & 7 )))){
If (backward) {str --;} else {STR ++ ;}
}
}
Return (char *) Str );
}
Char * xstrpbrk (const char * string, const char * end_ptr, const char * Control)
{
Const unsigned char * tail = (const unsigned char *) end_ptr;
Const unsigned char * STR = (const unsigned char *) string;
Const unsigned char * CTRL = (const unsigned char *) control;
Unsigned char map [32];
Int count;
Int backward;
// Clear out bit map
For (COUNT = 0; count <32; count ++ ){
Map [count] = 0;
}
// Set bits in control map
While (* CTRL ){
Map [* Ctrl> 3] | = (1 <(* CTRL & 7 ));
CTRL ++;
}
// 1st char in control map stops search
Backward = (STR <= tail | null = tail )? 0: 1;
While (* STR & Str! = Tail)
{
If (Map [* STR> 3] & (1 <(* STR & 7 )))){
Return (char *) Str );
}
If (backward) {str --;} else {STR ++ ;}
}
Return NULL;
}