Re: remove spaces from a string and Complexity



Richard Heathfield wrote:
DanielJohnson said:

On Feb 19, 5:08 pm, "DanielJohnson" <diffuse...@xxxxxxxxx> wrote:
I am writing a program in which I am removing all the spaces from the
string. I thought that I could do it two ways. One was parsing the
string character by character and copying onto another output string.
But this was trivial.
The other option is to use pointers and shift all the characters
after the space by one space to the left. I did this program using
pointers and then using array too and I get segmentation fault. What
is going wrong in here ?


[snip op's code]
[snip Richard's explaination]


What you want to do is fairly easy, actually, and - not surprisingly - the answer is in K&R2, on page 47:

/* squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for(i = j = 0; s[i] != '\0'; i++)
if(s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}

Here's my own version:

void delchar(char *s, char c)
{
char *t = s;
for(;*s;(*s != c) ? *t++ = *s++ : *s++)
{
continue;
}
*t = '\0';
}

I've seen functions written as above, however I'm still a little confused about one point - C passes by value therefore with your above function wouldn't the following behave incorrectly (incorrectly as in not modify the contents referenced by the first parameter but instead modify a copy of it):

int main(void)
{
char *p = NULL;

p = malloc(20);

strcpy(p, " me");

delchar(p, ' ');

return(0);
}

That being said, shouldn't the above function be written as such (i added 'ptr' to make it a little easier to read, at least in my perspective):

void delchar(char **s, char c)
{
char *t = *s;
char *ptr = *s;
for(;*ptr;(*ptr != c) ? *t++ = *ptr++ : *ptr++)
{
continue;
}
*t = '\0';
}

[snip]

The above has confused me since day 1 of learning the language. I've long since learned to accept that in order to modify the original contents from another function a pointer to that data is needed.
.



Relevant Pages