Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Compressing a string in C

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

    rcgldr

    User Avatar
    Homework Helper

    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: Feb 29, 2012
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Compressing a string in C
  1. Strings in c. (Replies: 3)

Loading...