[Original] use C to implement trim () Functions

Source: Internet
Author: User

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

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.