I'm trying to make a program that deletes extra white spaces from a string. It should keep one space but delete any extra.
I wrote this code, which works up until the point I have to change the passed pointer's address to the new string I made in the function. I have read that this is not possible without making a pointer to a pointer. The problem is, for my assignment, I can't change the argument types.
Is there any way to do this without making a new string, or is there a way to change the pointer address of s to point to newstr?
My code:
void str_trim(char *s)
{
// your code
char newstr[200];
char *newstrp = newstr;
while (*s != '\0')
{
if (*s != ' ')
{
*newstrp = *s;
*newstrp++;
*s++;
}
else if (*s == ' ')
{
*newstrp = *s;
*newstrp++;
*s++;
while (*s == ' ')
{
s++;
}
}
else
{
*newstrp = *s;
*newstrp++;
*s++;
}
}
s = &newstr;
}
Edit: This is what I ended up using
char *p = s, *dp = s;
while (*dp == ' ')
dp++;
;
while (*dp)
{
if (*dp == ' ' && *(dp - 1) == ' ')
{
dp++;
}
else
{
*p++ = *dp++;
}
}
if (p > s && *(p - 1) == ' ')
{
p--;
}
*p = '\0';
Is there any way to do this without making a new string, or is there a way to change the pointer address of
sto point tonewstr?
There is no way to change the caller's variable without changing the argument type of s to char**. So, that leaves you with two choices:
You can change your function to return the new char* pointer. However, you can't return a pointer to a local variable, which means you will have to malloc() the new string, and then the caller will have to free() it (probably not what you want to do), eg:
char* str_trim(char *s)
{
char *newstr = malloc(200);
//...
return newstr;
}
char *s = str_trim(...);
...
free(s);
Online Demo
Otherwise, simply get rid of the local char[] buffer altogether, and just modify the contents of s in-place (this is your only option if you can't change the signature of str_trim() at all), eg:
void str_trim(char *s)
{
char *newstr = s;
while (*s != '\0')
{
if (*s != ' ')
{
*newstr = *s;
++newstr;
++s;
}
else
{
*newstr = *s;
++newstr;
++s;
while (*s == ' ')
{
++s;
}
}
}
*newstr = '\0';
}
char s[] = "...";
str_trim(s);
Online Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With