helpppp! please :) remove char from string

hi,
I've to do a function that removes char(input by user) from string , only if it appeared and to reduce spaces.

for instance: string = abcabcd ; and the char= c/
the return string is : ababd

I did as follow; and I don't know the fix answer :/
please I must submit it in for 2 hours....
void removeChar(char string2[SIZE], char ch)
{
//---NOTE--- its not completely works - there is a problem i.
int read = 0, write = 0;

while (string2[read] != '\0')
{
if(string2[read]!= ch)
{
read++;
write++;
}
else
{
string2[write]= string2[read+1];
string2[write+1]= string2[read+1];
read++;
}

if(string2[read+1]=='\0' && string2[write+1]==ch)
{
string2[write+1] = '\0';
}
}

cout << string2 << endl;
}


Thankuuuu
closed account (Dy7SLyTq)
http://www.cplusplus.com/reference/string/string/
i would use this with the find method
hey,

I cannot use the oper "erase "
because I need to do the computation by self.

u understand?
1
2
3
4
5
6
7
8
9
10
11
12
13
char * removeChar( char *s, char c )
{
	char *p = s, *q = s;

	while ( *p && *p != c ) ++p, ++q;

	do
	{
		if ( *p != c ) *q++ = *p;
	} while ( *p++ );

	return s;
}
You can call the function the following way

1
2
3
4
5
char string[] = "abcabcd';

std::cout << string << std::endl;

std::cout << removeChar( string, 'c' ) << std::endl;  
Last edited on
@vlad that's a neat solution.
thank you vlad!
have a good week meantime ;)
Topic archived. No new replies allowed.