Thursday 2 August 2012

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

//solution1---using pointers

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]



//solution2--without using pointers


// The trim() function...
char* trim(char *str)
{
int i=0,j=0;
while(str[j] != '\0')
{
if(str[j] == ' ')
j++;
str[i++]=str[j++];
}
str[i]='\0';
return str;
}

No comments:

Post a Comment