-
String Remove problem
I am trying to make a function that takes a string and removes all occurences of a specified character then returns the new string. The code I wrote generates an error, and I am having no luck debugging the problem. Can someone point me in the write direction? I am using visual studio 2003.
Code:
char* remove(char *str, char c)
{
char *str2="";
while(*str != '\0')
{
if(*str!=c)
{
*str2=*str;
}
str++;
str2++;
}
return str2;
}
int _tmain()
{
char* str = "This is a test";
char c= ' ';
remove(str, c);
// cout<<endl<<remove(str, c);
}
-
In C++, why not use std::string?
Don't try to return a pointer to a local.
Only write to modifiable memory.
Search the board.
-
That points to an immutable string literal. You want it to point to some free space. You might do something like;
Code:
char *str2 = new char[strlen(str) + 1];
And then delete[] the return of remove(..) to avoid a memory leak. Alternately, you could pass the function an existing character buffer pointing to free space.
-
There are some constraints that I can not remove on the code. The pointers can not be removed.
-
When I return my new string I am getting a trash value that is not useful.
-
No I am supposed to return another string that contains the proper output. The original string should remain unchanged.
-
[Sorry for the deletion. I reread that.]
And I suppose your function cannot change to receive a destination string?
-
You modify the value of your str2. You never null-terminate it, and return a pointer to where the null-terminator should be. Your algorithm has something a little wrong. To fix the first problem, do something like:
Code:
char *space = new char[strlen(str) + 1];
char *temp = space;
...
... // Operate on 'temp'
...
return space;
-
Okay I fixed the remove method to look like this
Code:
char* remove(char *str, char c)
{
char *space = new char[strlen(str) + 1];
char *str2= space;
while(*str != '\0')
{
if(*str!=c)
{
*str2=*str;
str2++;
}
str++;
}
*str2='\0';
return space;
}
but why do I return space and not temp?
-
Because you change the value of the pointer so by the end you would be returning a pointer to the end of the string. If you just keep a pointer to the start of the space, and manipulate it with another (or bypass this whole thing entirely with array notation), then you can just return the pointer to the new space string.
-
Thanks Tonto you cleared all that up for me. How would you have done this if you were given the problem, and why would you do it that way? I am still learning, and I want to know the right way to do things.