Compressing a string in C

  • Thread starter xortan
  • Start date
  • #1
78
1

Main Question or Discussion Point

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
 

Answers and Replies

  • #2
78
1
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 doesnt 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;
}
 
  • #3
76
0
you will need to walk through the entire string and shift the string backwards one each time you find whitespace
 
  • #4
78
1
I thought thats why I had --s there. It is able to compress spaces but not tabs
 
  • #5
78
1
Sorry actually I think its working, wasn't testing it properly I guess
 
  • #6
76
0
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:
  • #7
191
3
Also, use code tags and you will retain the indentation, extra spaces, etc.
 
  • #8
rcgldr
Homework Helper
8,691
522
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:

Related Threads on Compressing a string in C

Replies
3
Views
2K
  • Last Post
Replies
7
Views
2K
  • Last Post
Replies
9
Views
2K
Replies
4
Views
569
Replies
6
Views
1K
  • Last Post
Replies
13
Views
1K
Replies
11
Views
838
Replies
6
Views
8K
Replies
2
Views
463
  • Last Post
Replies
2
Views
4K
Top