简体   繁体   中英

how to remove extra spaces from string in C

I have an string that have an extra spaces string, for example:

char * s = "  foo    baa       ";

I want to conver it to:

foo baa

I have wrote this function:

void trim (char ** src)
    {
        char * p = strdup(* src);
        char * ret = malloc(strlen(*src) + 1);
                assert(ret != NULL);
        char * token;
        token = strtok(p, " \t");
        while( NULL != token ) {
            while (*token) {
                 *(ret ++) = *(token ++);
            }
            token = strtok(NULL, " \t");
        }

        printf("ret = %s\n", ret);
    }

but it given for me an empty string from ret variable value. someone may point out my mistake? thanks in advance.

You are incrementing ret in your while, store the original address or use subscript to access different chars of ret .

    // snip
    char * ret = malloc(strlen(*src) + 1);
            assert(ret != NULL);
    char * ret_start = ret;
    //snap
    printf("ret_start = %s\n", ret_start);

Other naive solution in c++(can be easily changed to c code )----- :)

initially count=0 and str -> your c++ string

for(i=0;i< str.size();i++)
{
        if(str[i]!=' ')
        {
                str[j++]=str[i];
                count=0;
        }
        else if(str[i]==' '&&count==0)
        {
                str[j++]=str[i];
                count =1;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM