Wednesday, August 15, 2007

Write your own trim() or squeeze() function to remove the spaces from a string.

#include < stdio.h >

char *trim(char *s);

int main(int argc, char *argv[])
{
char str1[]=" Hello I am Good ";
printf("\n\nBefore trimming : [%s]", str1);
printf("\n\nAfter trimming : [%s]", trim(str1));

getch();
}


// The trim() function...

char *trim(char *s)
{
char *p, *ps;

for (ps = p = s; *s != '\0'; s++)
{
if (!isspace(*s))
{
*p++ = *s;
}
}

*p = '\0';

return(ps);
}


And here is the output...


Before trimming : [ Hello I am Good ]
After trimming : [HelloIamGood]



Another version of this question requires one to reduce multiple spaces, tabs etc to single spaces...

8 comments:

riya said...

cnt we do this without using pointers?

praveen said...

can u just tell how to remove the beginning and end white spaces alone

Anonymous said...

char *trim_string(char *str)
{
int i=0,j=0;
while(str[j] != '\0')
{
if(str[j] == ' ')
j++;
str[i++]=str[j++];
}
str[i]='\0';
return &str;
}

sandeep kumar said...

Thanks for the info. It is very helpful.

Regards
Educational site

Get jobs info at Educational site

Anonymous said...

I usually do not create a bunch of comments, but I looked at a
lot of responses on this page "Write your own trim() or squeeze() function to remove the spaces from a string.".
I do have some questions for you if you tend not to mind.

Could it be just me or does it look like like some of the responses come across as if
they are left by brain dead folks? :-P And, if you are posting on other social sites, I would like to keep up with you.
Would you post a list of all of your social community pages like your Facebook
page, twitter feed, or linkedin profile?

Here is my site: Email Console

Anonymous said...

I am sure this paragraph has touched all the internet viewers, its really really fastidious post on building up new webpage.



My homepage - healthy diet plan

Anonymous said...

I absolutely love your blog and find nearly all of your post's to be precisely what I'm looking for.
Do you offer guest writers to write content in your case? I wouldn't mind creating
a post or elaborating on some of the subjects you write about here.
Again, awesome weblog!

my web page Best SAD Light

Leslie Lim said...

It is great to have the opportunity to read a good quality article with useful information on topics that plenty are interested on.

www.imarksweb.org