pointer c string

Nov 26, 2012 at 3:49am
Hey I am trying to work on a problem:
----------------------------------------------------------------------------
Write a function named removeS that accepts one character pointer as a parameter and returns no value. The parameter is a C string. This function must remove all of the upper and lower case 's' letters from the string. The resulting string must be a valid C string.

Your function must declare no more than one local variable in addition to the parameter; that additional variable must be of a pointer type. Your function must not use any square brackets and must not use the strcpy library function.

int main()
{
char msg[50] = "She'll be a massless princess.";
removeS(msg);
cout << msg; // prints he'll be a male prince.
}

---------------------------------------------------------------------------
Since I'm only allowed to make one local variable of a pointer, I'm guessing making a new c string is out of the question. I made a for loop that checks for an 's' and replaces it with the next letter.
1
2
3
4
5
6
7
8
9
10
11
12
void removeS(char* message)
{
	char* ptr = message;
	for(; *ptr != '\0'; ptr++)
	{
		while(*ptr == 's' || *ptr == 'S')
		{
			*ptr = *(ptr+1);
			
		}
	}
}

Is this the right way to go about the problem? If so, how can I solve the problem of the rest of the characters?(She'll would become hhe'll)?
Or is there another more straightforward way of doing it
Last edited on Nov 26, 2012 at 4:01am
Nov 26, 2012 at 4:03am
Nice input string.

Your hint is helpful: the simple way to go about it is to create another pointer, and run through the string with two pointers. One (the original function parameter) stepping through every character. The other (the new one) also stepping through every character, but skipping any 's' or 'S'. The loop would copy the character from the second pointer to the first:

1
2
3
4
5
6
7
8
9
10
void removeS(char* message)
{
    for(char* p = message; *p; )
    {
        while(*p == 's' || *p == 'S')
            ++p;
        *message++ = *p++;
    }
    *message = '\0';
}
Nov 26, 2012 at 4:11am
Ah good idea thanks!
in the for loop, what is the purpose of the condition statement *p? Isn't it not checking for anything?
Last edited on Nov 26, 2012 at 4:12am
Nov 26, 2012 at 4:12am
it's shorthand for *p != '\0' in this case
Nov 26, 2012 at 4:27am
oh ok, sorry is
*message++ = *p++;

also shorthand for

1
2
3
*message = *p
message++;
p++;

?
Nov 26, 2012 at 10:43am
Yes, *p++ = *q++ is also a very common C idiom, I think it is more recognizable than something like
1
2
3
4
5
6
for(char* p = message; *p != '\0'; ++p, ++message)
{
     while(*p == 's' || *p == 'S')
         ++p;
     *message = *p;
}

(although this is probably a better-looking use of a for-loop).
Nov 26, 2012 at 11:05am
My five cents

1
2
3
4
5
6
7
8
9
void remove( char *s )
{
	char *p = s;

	do
	{
		if ( *s != 's' && *s != 'S' ) *p++ = *s;
	} while ( *s++ );
}
Topic archived. No new replies allowed.