Home > Net >  Removing whitespace from string in C using pointer to pointer
Removing whitespace from string in C using pointer to pointer

Time:01-14

I'm having some issues trying to remove all whitespace from a string (for example: "a b c x") using a method that takes a double pointer argument. I have solved it using single pointers and using strings in c , but I wanted to get this working as well for curiosity's sake :)

This is what I've tried:

void remove_whitespace(char** s)
{
    char **rd; // "read" pointer
    char **wr; // "write" pointer

    rd = wr = s; // initially, both read and write pointers point to beginning of string

    while ( *rd != 0 ) // while not at end of string
    {
    while ( isspace( **rd ) ) // while rd points to a whitespace character
        rd  ;                  // advance rd
    *wr   = *rd  ;           // copy *rd to *wr, advance both pointers
    }
    *wr = 0;                   // terminate the result

    printf("\nsquished: %s\n", s);
}

CodePudding user response:

All errors in this function stem from confusing the level of indirection. Using char** over char* increases the level of indirection which affects every usage of these variables.

Simply converting the function to use char* makes it much clearer:

void remove_whitespace(char* s)
{
    char *rd; // "read" pointer
    char *wr; // "write" pointer

    rd = wr = s; // initially, both read and write pointers point to beginning of string

    while ( *rd != 0 ) // while not at end of string
    {
        if (isspace( *rd ) ) // while rd points to a whitespace character
        {
            rd  ;                  // advance rd
            continue;
        }
        *wr   = *rd  ;           // copy *rd to *wr, advance both pointers
    }
    *wr = 0;                   // terminate the result

    printf("\nsquished: %s\n", s);
}

CodePudding user response:

  1. It is good if function returns something.
  2. Your local worker pointers do not have to be pointers to pointers
char **remove_whitespace(char **s)
{
    char *rd; // "read" pointer
    char *wr; // "write" pointer

    rd = wr = *s; 

    while ( *rd) // while not at end of string
    {
    while ( isspace( (unsigned char)*rd ) ) // while rd points to a whitespace character
        rd  ;                  // advance rd
    *wr   = *rd  ;           // copy *rd to *wr, advance both pointers
    }
    *wr = 0;                   // terminate the result

    printf("\nsquished: %s\n", *s);
    return s;
}

Usage:

int main(void)
{
    char z[] = "asdas das as \r dfds \n dsa \t";
    char *p = z;

    remove_whitespace(&p);
}

https://godbolt.org/z/Ex337TE6n

  • Related