How to Fix Errors in C String Compression Function?

  • Thread starter Thread starter xortan
  • Start date Start date
  • Tags Tags
    String
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
7 replies · 3K views
xortan
Messages
76
Reaction score
1
I am trying to write a function that will detect multiple spaces, tabs, and newlines and replace it with a single string. Here is what I got so far, I keep getting errors about using a void expression and making an integer from a pointer without a cast. Please help I am really new to programming.

void compress(char* s);


int main()
{
char a[] = "Hello World";

printf("%s", compress(a));

getchar();
}

void compress(char* s)
{

char *srcIx = s;
char *destIx;

while(*srcIx)
{
if(*srcIx != ' ' || *srcIx != '\t' || *srcIx != '\n')
*(destIx++) = *srcIx;

srcIx++
}

*s = destIx;

}

Am I even going about this problem the right way? Also when I enter a bunch of spaces into the box PF seems to compress it already :P Imagine there are a bunch of spaces between hello and world
 
Physics news on Phys.org
Sorry for the double post but was playing around with it and got it to be able to remove spaces and got figured out proper way to call function from main. Anyways here is some updated code, I am trying to detect tabs and newlines now. I tried adding some logical ANDS and ORS to the if statemant and while loop but doesn't detect it.

void compress(char* s)
{

char *srxIx = s;
for(; *s; ++s)
{
*srcIx++ = *s;
if(isspace(*s) || *s == '\t' || *s == '\n')
{
do
++s;
while(isspace(*s) || *s == '\t' || *s == '\n')
--s;
}
}
*srxIx = 0;
}
 
you will need to walk through the entire string and shift the string backwards one each time you find whitespace
 
I thought that's why I had --s there. It is able to compress spaces but not tabs
 
Sorry actually I think its working, wasn't testing it properly I guess
 
Your do while loops syntax is off

do
{
//CODE
}while(condition);

--s; is not replacing the string it is only decrementing the place it was previously, you need to physically replace after you decrement the string.
 
Last edited:
Also, use code tags and you will retain the indentation, extra spaces, etc.
 
You don't need the --s. You want to increment s past any non-leading white space characters, with the rest of the code copying from s to srcIx (not sure why you chose this name for a destination pointer).
 
Last edited: