Trim () function written in C Language

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.