0

this code takes out the spaces in between and i want to shrink this code a bit.
like in function modify. It doesnt work if i take out the if(s[i] == ' ')
I want to make this code work without using that.
Any help??

#include<stdio.h>
#include<stdlib.h>

char* modify(char*);

void main()
{
        char* str = malloc(100 * sizeof(char));
        char* mstr;

        printf("Enter a string: ");
        gets(str);

        mstr= modify(str);
        printf("String after removing spaces: %s \n\n",mstr);
}

char* modify(char *s)
{
        int i,j=0;
        static char temp[200];
        for(i = 0; s[i] != '\0'; i++)
        {
                if(s[i] == ' ')
                {}
                else
                {
                        temp[j] = s[i];
                        j++;
                }
        }
        temp[j] = '\0';
        return temp;
}

Edited by Reverend Jim: Fixed formatting

2
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by wildgoose
0
char* modify(char *s)
{
	int i,j=0;
	static char temp[200];

	for(i = 0; s[i]; i++)
	{
		if(s[i] != ' ')
		{
			temp[j] = s[i];
			j++;
		}
	}

	temp[j] = '\0';
	return temp;
}
0
char* modify(char *s)
{
	int i,j=0;
	static char temp[200];

	for(i = 0; s[i]; i++)
	{
		if(s[i] != ' ')
		{
			temp[j] = s[i];
			j++;
		}
	}

	temp[j] = '\0';
	return temp;
}

Thanks uhh "wildgoose"
that was simple i guess

0

Binary size is still the same. I only removed the empty comparison, and the more verbose declaration!

You could use a strtok function to make it smaller if that's allowed!

char *p = strtok( s, " " );
*temp = 0;

while (NULL != p)
{
    strcat( temp, p );
     p = strtok( NULL, " " );
}

But that's really no smaller then what you already had and in fact will run slower because of the overhead of the strtok and the strcat!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.